fs模块

检测文件是否存在

// 检测文件是否存在
fs.exists('readme.md', function(exists) {
  console.log(exists);
})

异步操作

// 新建目录
fs.mkdir('file', 0777, function(err) {
    if (err) throw err;
    console.log('新建文件夹成功');
});

// 写入文件
fs.writeFile('./file/1.md', '随便写入一句话吧', function(err) {
    if (err) throw err;
    console.log('文件写入成功')
});

// 读取文件
fs.readFile('./file/1.md', 'utf8', function(err, data) {
    if (err) throw err;
    console.log(data);
});

同步操作

// 新建目录
fs.mkdirSync('file', 0777);
console.log('新建file文件夹成功');

// 写入文件
fs.writeFileSync('file/1.md', '随便写入一句话吧', 'utf8');
console.log('新建文件成功');

// 读取文件
var data = fs.readFileSync('file/1.md', 'utf8');
console.log('读取文件:' + data);

读取目录

fs.readdir('file', function(err, files) {
    if (err) throw err;
    var length = files.length;
    console.log('一共有' + length + '个文件');
});

判断是文件还是目录

fs.stat('./fs.js', function(err, stat) {
    if (stat.isFile())
        console.log('这是个文件');
    else if (stat.isDirectory())
        console.log('这是个目录');
});

监听文件

// 监听文件
fs.watchFile('readme.md', function(curr, prev) {
    console.log('the current mtime is: ' + curr.mtime);
    console.log('the previous mtime was: ' + prev.mtime);
});

// 解除监听
setTimeout(function() {
    fs.unwatchFile('readme.md');
}, 1000);

读写数据流

// 读取数据流
var file = fs.createReadStream('readme.md');
var str = '';
file.on('data', function(data) {
    str += data;
});
file.on('end', function() {
    console.log(str);
});

// 写入数据流
var file = fs.createWriteStream('readme.md', {encoding: 'utf8'});
file.write('写入一句
');
file.write('再写入一句
');
file.write('最后再来一局');
file.end();
 
原文地址:https://www.cnblogs.com/SharkChilli/p/8124199.html