Checking if writeFileSync successfully wrote the file

Javascriptnode.js

Javascript Problem Overview


I have a simple route defined with express.js:

exports.save = function (request, response)
{
    var file = request.body.file;
    var content = request.body.content;

    var saved = false;

    if (fs.existsSync( file ))
    {
        saved = fs.writeFileSync(file, content, 'utf8');
    }

    console.log( saved ); // undefined or false, never true

    response.send(saved ? 200 : 500, saved ? 'saved' : 'error'); // 500, error
};

Is if (typeof saved === 'undefined') saved = true; the only option? Feels hacky.

Javascript Solutions


Solution 1 - Javascript

According to node.js source-code fs.writeFileSync doesn't return anything.

It throws an Error object if something goes wrong. So you should write fs.writeFileSync(file, content, 'utf8'); within a try-catch block.

Solution 2 - Javascript

fs.writeFileSync does not return any value, if there is no exception happens that means the save succeeded; otherwise failed.

you may want to try the async version of file read

fs.exists(file, function (exists) {
  if (exists) {
    fs.writeFiles(file, content, 'utf-8', function (err) {
      if (err) {
        response.send("failed to save");
      } else {
        response.send("succeeded in saving");
      }
  } else {
    console.log('file does not exists');
  }
}

Solution 3 - Javascript

 fs.exists(file, function (exists) {
  if (exists) {
    fs.writeFiles(file, content,  err=> {
      if (err)   res.status(500).send({error: "failed to save"});
       else    res.status(200).send({message : "succeeded in saving"});
  } else {
    res.status(404).send({error: "file not exists"})
  }
}

Use async instead of sync. This will work.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiontomsseisumsView Question on Stackoverflow
Solution 1 - JavascriptfardjadView Answer on Stackoverflow
Solution 2 - JavascriptShupingView Answer on Stackoverflow
Solution 3 - JavascriptRohit SoniView Answer on Stackoverflow