Nodejs 操作文件流 fs 同步异步

// 默认读取文件是异步的
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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值