第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

同步異步的問題

同步異步的問題

徐錦杰 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:為什么第一個函數(shù)的回調函數(shù)會是后執(zhí)行的?
查看完整描述

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 關注
  • 1426 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網(wǎng)微信公眾號