// 默认读取文件是异步的
var fs = require('fs');
console.log('begin read a file');
var data = 321;
fs.readFile('./wechat-menu.json', function(err, data){
data = data;
console.log(data);
});
console.log('finished read a file');
console.log(data);
console.log('finished read a file');
// 结果如下
begin read a file
finished read a file
321
finished read a file
<Buffer 7b 0d 0a 20 20 22 62 75 74
同步读取文件
var fs = require('fs');
console.log('begin read a file');
var data = fs.readFileSync('./wechat-menu.json');
data = JSON.parse(data);
console.log(data.button);
console.log('finished read a file');
// 结果如下
begin read a file
[ { name: '我的账号',
sub_button: [ [Object], [Object], [Object], [Object], [Object] ] }] } ]
finished read a file
其他读取文件api
// 写入文件
fs.writeFile('delete.txt','1234567890',function(err){
console('youxi!');
});
// 删除文件
fs.unlink('delete.txt', function(){
console.log('success');
});
// 修改文件名称
fs.rename('delete.txt','anew.txt',function(err){
console.log('rename success');
// 查看文件状态
fs.stat('anew.txt', function(err, stat){
console.log(stat);
});
});
// 判断文件是否存在
fs.exists('a.txt', function( exists ){
console.log( exists );
});
// 将数据添加到文件末尾
fs.appendFile( filename, data, [optins], callback );
转载自:https://blog.csdn.net/iteye_13003/article/details/82604971
本人博客地址:http://m.readers.fun