一、同步实现
// 使用fs模块,创建一个目录fs
// 使用fs模块,在目录中创建一个test.txt文件,往里面写入hello world字符串
// 使用fs模块,复制之前写的test.txt文件,并粘贴到同一文件夹下改名为hello.txt
// 使用fs模块,读取hello.txt文件的大小和创建时间
// 使用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('创建大小:'+ fs.statSync('fs/hello.txt').size);
console.log('创建时间:'+ 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');
二、同步实现(不同一个文件下)
//使用fs模块,创建一个目录fs
var fs = require('fs');
fs.mkdir('fs',function(err){
if(err) throw err;
console.log('创建目录成功!');
})
// 使用fs模块,在目录中创建一个test.txt文件,往里面写入hello world字符串
var fs = require('fs');
var data = 'hello world';
fs.writeFile('fs/test.txt',data,function(err){
if(err) throw err;
console.log('写入成功!');
});
// 使用fs模块,复制之前写的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文件的大小和创建时间
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('创建时间:'+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() 读取目录内容
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) 删除文件夹