javascript - Node.js fs.writeFileSync with options and callback and error hundler? - Stack Overflow

I looked at Node.js Documentation and I didn't find how to apply options (settings) and a callback

I looked at Node.js Documentation and I didn't find how to apply options (settings) and a callback function with error handling. And I have to use .writeFileSync (not asynchronous .writeFile):

const settings = {
        flags: 'w',
        encoding: null, //must be null
        mode: 0o666,
        autoClose: true //not found this option
      };

fs.writeFileSync(dest, buff, settings);

Before I used:

fs.writeFileSync(dest, buff, function (err) {
  if (err) { 
    ... 
  } else { ... console.log("OK") }

})

but I found that I have to apply encoding: null, option to prevent any modifications of source data (buff), in other case the file can be broken.

Edit: After amazing answers and explanations I would like to say that I was confused with Node.js Documentation : fs.writeFileSync(file, data[, options]) is

The synchronous version of fs.writeFile().

Since this is version of fs,writeFile() method I thought it can have the same versions of function's signature...

And here my final version of code, but it still has the issue with decoding of binary files (can be any file types) (* by the way when I tried to use Axios.js I saw Errors: "Request failed with Status Code 500):

function download(url, dest, fileName, callback) {

  //import http from 'http';
  var request = http.get(url, function (response) {

    var bodyParts = [];
    var bytes = 0;

    response.on("data", function (c) {
      bodyParts.push(c);
      bytes += c.length;
    })

    response.on("end", function () {

      // flatten into one big buffer
      var buff = new Buffer(bytes);
      var copied = 0;

      for (var i = 0; i < bodyParts.length; i++) {
        bodyParts[i].copy(buff, copied, 0);
        copied += bodyParts[i].length;
      }

      const settings = {
        flags: 'w',
        encoding: null, //not applicable / no changes
        mode: 0o666
      };

      try {
        fs.writeFileSync(dest, buff, settings);

        let msgOK = {
          filename: fileName,
          status: 'OK',
          text: `File downloaded successfully`
        }
        if (callback) callback(msgOK);
        console.log(msgOK.text);
        isLoading = false; //IMPORTANT! 

      } catch (err) {
        console.error(err.stack || err.message);

        let msgErr = {
          filename: fileName,
          status: 'ERROR',
          text: `Error in file downloading ${err.message}`
        }
        ERRORS.push(err);
        if (callback) callback(msgErr);
      }

    })

  })

}

I looked at Node.js Documentation and I didn't find how to apply options (settings) and a callback function with error handling. And I have to use .writeFileSync (not asynchronous .writeFile):

const settings = {
        flags: 'w',
        encoding: null, //must be null
        mode: 0o666,
        autoClose: true //not found this option
      };

fs.writeFileSync(dest, buff, settings);

Before I used:

fs.writeFileSync(dest, buff, function (err) {
  if (err) { 
    ... 
  } else { ... console.log("OK") }

})

but I found that I have to apply encoding: null, option to prevent any modifications of source data (buff), in other case the file can be broken.

Edit: After amazing answers and explanations I would like to say that I was confused with Node.js Documentation : fs.writeFileSync(file, data[, options]) is

The synchronous version of fs.writeFile().

Since this is version of fs,writeFile() method I thought it can have the same versions of function's signature...

And here my final version of code, but it still has the issue with decoding of binary files (can be any file types) (* by the way when I tried to use Axios.js I saw Errors: "Request failed with Status Code 500):

function download(url, dest, fileName, callback) {

  //import http from 'http';
  var request = http.get(url, function (response) {

    var bodyParts = [];
    var bytes = 0;

    response.on("data", function (c) {
      bodyParts.push(c);
      bytes += c.length;
    })

    response.on("end", function () {

      // flatten into one big buffer
      var buff = new Buffer(bytes);
      var copied = 0;

      for (var i = 0; i < bodyParts.length; i++) {
        bodyParts[i].copy(buff, copied, 0);
        copied += bodyParts[i].length;
      }

      const settings = {
        flags: 'w',
        encoding: null, //not applicable / no changes
        mode: 0o666
      };

      try {
        fs.writeFileSync(dest, buff, settings);

        let msgOK = {
          filename: fileName,
          status: 'OK',
          text: `File downloaded successfully`
        }
        if (callback) callback(msgOK);
        console.log(msgOK.text);
        isLoading = false; //IMPORTANT! 

      } catch (err) {
        console.error(err.stack || err.message);

        let msgErr = {
          filename: fileName,
          status: 'ERROR',
          text: `Error in file downloading ${err.message}`
        }
        ERRORS.push(err);
        if (callback) callback(msgErr);
      }

    })

  })

}
Share Improve this question edited Apr 26, 2018 at 2:44 Alex Pilugin asked Apr 26, 2018 at 1:21 Alex PiluginAlex Pilugin 7052 gold badges11 silver badges39 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 4

The synchronous version of any file system method does not accept a callback and they will throw in case of error, so you should catch it.

When using the synchronous form any exceptions are immediately thrown. You can use try/catch to handle exceptions or allow them to bubble up.

try {
    fs.writeFileSync(dest, buff);
    // You don't need callback, the file is saved here
} catch(e) {
    console.error(e);
}

There's no setting autoClose for fs.writeFileSync the only available options are:

encoding <String> | <Null> default = 'utf8'
mode <Number> default = 0o666
flag <String> default = 'w'

Last but not least, you should update your node version, since Node.js 4.x end of life is in less than a week. (2018-04-30)

fs.writeFileSync throws an error
so you can do

try {
  fs.writeFileSync(dest, buff)
} catch (err) {
  // do something
}

and you wouldn't need callback because it's synchronous
just put your code after calling writeFileSync

I suggest that you can use

try {
  fs.writeFileSync(dest, buff, settings);
} catch(e) {
  // do your error handler
}   

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745104795a4611492.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信