fs.writeFile() doesn't return callback

青春壹個敷衍的年華 提交于 2019-12-22 04:53:08

问题


I'm trying to write a file with the users authentication data to the disk. To achieve this I wrote the following function:

function writeAuthFile(data, success, fail) {
  var fs = require('fs');
  fs.writeFile('auth.json', JSON.stringify(data), function(error) {
    if(error) { 
      console.log('[write auth]: ' + err);
        if (fail)
          fail(error);
    } else {
      console.log('[write auth]: success');
        if (success)
          success();
    }
  });
}

But it never calls the callback. I looked at the nodeJS docs for fs and it all seems to check out. Also all other asynchronous execution seems to have halted.

This is the first time I'm developing something serious in nodeJS so my experience in this environment is not that much.


回答1:


Your code looks fine, I copy&paste and run it by simply calling writeAuthFile({test: 1});, file auth.json was created. So, mb error somewhere higher? add console.log after var fs = require('fs'); line and test.




回答2:


the only thing i see thats off, is that if it fails it tries to log "err" instead of "error"

if(error) {
    console.log('[write auth]: ' + err); //<-this should be "error" and not "err"


来源:https://stackoverflow.com/questions/28545043/fs-writefile-doesnt-return-callback

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!