Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if writeFileSync successfully wrote the file

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.

like image 809
tomsseisums Avatar asked Mar 21 '13 09:03

tomsseisums


People also ask

What does writeFileSync return?

writeFileSync doesn't return anything. It throws an Error object if something goes wrong. So you should write fs.

What is the difference between writeFile and writeFileSync?

The only difference between writeFile and writeFileSync is in catching and handling the errors; otherwise, all parameters mentioned are available in both functions.


2 Answers

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.

like image 85
fardjad Avatar answered Sep 23 '22 20:09

fardjad


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');   } } 
like image 31
Shuping Avatar answered Sep 21 '22 20:09

Shuping