为了账号安全,请及时绑定邮箱和手机立即绑定

同步异步的问题

同步异步的问题

徐锦杰 2017-06-02 15:22:42
var data='Hello,Node.js'; fs.writeFile('output.txt',data,function(err){ if (err) { console.log(err); }else { console.log('ok.'); } }); fs.stat('output.txt',function(err,stats){ if (err) { console.log(err); }else { console.log('isFile:'+stats.isFile()); console.log('isDirectory:'+stats.isDirectory()); if (stats.isFile()) { console.log('size:'+stats.size); console.log('birth time:'+stats.birthtime); console.log('modified time:'+stats.mtime); } } }); 输出内容为 isFile:true isDirectory:false size:0 birth time:Fri Jun 02 2017 14:47:28 GMT+0800 (CST) modified time:Fri Jun 02 2017 15:16:04 GMT+0800 (CST) ok. 问1:前面做了写入操作,下面显示的最后更改时间也是运行代码的时间,为什么size是0? 问2:为什么第一个函数的回调函数会是后执行的?
查看完整描述

1 回答

已采纳
?
ruibin

TA贡献358条经验 获得超213个赞

fs.writeFile = function(path, data, options, callback) {
  var callback = maybeCallback(arguments[arguments.length - 1]);
  if (util.isFunction(options) || !options) {
    options = { encoding: 'utf8', mode: 438 /*=0666*/, flag: 'w' };
  } else if (util.isString(options)) {
    options = { encoding: options, mode: 438, flag: 'w' };
  } else if (!util.isObject(options)) {
    throw new TypeError('Bad arguments');
  }
  assertEncoding(options.encoding);
  var flag = options.flag || 'w';
  fs.open(path, options.flag || 'w', options.mode, function(openErr, fd) {
    if (openErr) {
      if (callback) callback(openErr);
    } else {
      var buffer = util.isBuffer(data) ? data : new Buffer('' + data,
          options.encoding || 'utf8');
      var position = /a/.test(flag) ? null : 0;
      writeAll(fd, buffer, 0, buffer.length, position, callback);
    }
  });
};

这是writeFile的源码,意思就是writeFile默认以'w'的方式打开,也就是打开文件的时候要先把文件内容置空。如果你想要追加打开,手动修改下配置。如:fs.writeFile('output.txt',data,{flag: 'w+'},function(err){});  

查看完整回答
反对 回复 2017-06-05
  • ruibin
    ruibin
    第二个问题,stat是获取文件的信息,理论上应该会先有文件信息然后才能做io操作,等会儿去看下源码。(如果你想保证顺序,要么在成功回调里面写,要么用writeFileSync这样就能百分百保证顺序。)
  • 1 回答
  • 1 关注
  • 1341 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信