一、同步實(shí)現(xiàn)
// 使用fs模塊,創(chuàng)建一個(gè)目錄fs
// 使用fs模塊,在目錄中創(chuàng)建一個(gè)test.txt文件,往里面寫(xiě)入hello world字符串
// 使用fs模塊,復(fù)制之前寫(xiě)的test.txt文件,并粘貼到同一文件夾下改名為hello.txt
// 使用fs模塊,讀取hello.txt文件的大小和創(chuàng)建時(shí)間
// 使用fs模塊,刪除fs目錄
var fs = require('fs');
fs.mkdirSync('fs',function(err){
});
var data = 'hello world';
fs.writeFileSync('fs/test.txt',data);
fs.copyFileSync('fs/test.txt','fs/hello.txt');
console.log('創(chuàng)建大?。?+ fs.statSync('fs/hello.txt').size);
console.log('創(chuàng)建時(shí)間:'+ fs.statSync('fs/hello.txt').ctime);
function deleteall(path) {
var files = [];
if(fs.existsSync(path)) {
files = fs.readdirSync(path);
files.forEach(function(file, index) {
var curPath = path + "/" + file;
if(fs.statSync(curPath).isDirectory()) { // recurse
deleteall(curPath);
} else { // delete file
fs.unlinkSync(curPath);
}
});
fs.rmdirSync(path);
}
};
deleteall('./fs');
二、同步實(shí)現(xiàn)(不同一個(gè)文件下)
//使用fs模塊,創(chuàng)建一個(gè)目錄fs
var fs = require('fs');
fs.mkdir('fs',function(err){
if(err) throw err;
console.log('創(chuàng)建目錄成功!');
})
// 使用fs模塊,在目錄中創(chuàng)建一個(gè)test.txt文件,往里面寫(xiě)入hello world字符串
var fs = require('fs');
var data = 'hello world';
fs.writeFile('fs/test.txt',data,function(err){
if(err) throw err;
console.log('寫(xiě)入成功!');
});
// 使用fs模塊,復(fù)制之前寫(xiě)的test.txt文件,并粘貼到同一文件夾下改名為hello.txt
var fs = require('fs');
fs.copyFile('fs/test.txt','fs/hello.txt',function(err){
if(err) throw err;
console.log('copy成功!');
});
// 使用fs模塊,讀取hello.txt文件的大小和創(chuàng)建時(shí)間
var fs = require('fs');
fs.readFile('fs/hello.txt','utf8',function(err,data){
if(err) throw err;
console.log(data);
var stat = fs.statSync('fs/hello.txt');
var createTime =stat.ctime;
var size = stat.size;
console.log('創(chuàng)建時(shí)間:'+createTime);
console.log('文件大小:'+size);
});
// 使用fs模塊,刪除fs目錄
var fs = require('fs');
function deleteall(path) {
var files = [];
if(fs.existsSync(path)) {
files = fs.readdirSync(path);
files.forEach(function(file, index) {
var curPath = path + "/" + file;
if(fs.statSync(curPath).isDirectory()) { // recurse
deleteall(curPath);
} else { // delete file
fs.unlinkSync(curPath);
}
});
fs.rmdirSync(path);
}
};
deleteall('./fs');
- existsSync() :路徑是否存在 ( 同步方法)
var fs = require('fs');
console.log('file是否存在:'+fs.existsSync('file'));
console.log('Stage_Two是否存在:'+fs.existsSync('Stage_Three/fs_all.js'));

- readdir() // readdirSync() 讀取目錄內(nèi)容
var fs = require('fs');
console.log(fs.readdir('Stage_Two','utf8',function(err,files){
if(err) throw err;
console.log('\n異步方法:');
console.log(files);
}));
console.log('同步方法:');
console.log(fs.readdirSync('Stage_Two'));

- 刪除
unlinkSync(path) // unlink(path) 刪除文件
remdir(path)\ rmdirSync(path) 刪除文件夾