Why my fs.readFileSync does not work

Problem

Why does this code not work? If I comment fs.readFileSync('file.html'); the code works and it creates the file 'file.html' But if I uncomment it the fs.writeFileSync does not work, and the program crashes with the error:

fs.js:427 return binding.open(pathModule._makeLong(path), stringToFlags(flags), mode); ^ Error: ENOENT, no such file or directory 'file.html' at Object.fs.openSync (fs.js:427:18) at Object.fs.readFileSync (fs.js:284:15) at Object. (/home/pedro/startupEngineering/hw3/Bitstarter/testrestler.js:15:6) at Module._compile (module.js:456:26) at Object.Module._extensions..js (module.js:474:10) at Module.load (module.js:356:32) at Function.Module._load (module.js:312:12) at Function.Module.runMain (module.js:497:10) at startup (node.js:119:16) at node.js:901:3

#!/usr/bin/env node


var fs = require('fs');
var rest = require('restler');

var restlerHtmlFile = function(Url) {
  rest.get(Url).on('complete', function(result) {
   fs.writeFileSync('file.html',result);
  });
};

if(require.main == module) {
  restlerHtmlFile('http://obscure-refuge-7370.herokuapp.com/');
  fs.readFileSync('file.html');
}

else {
 exports.checkHtmlFile = checkHtmlFile;
}
Problem courtesy of: Pedro

Solution

Change

var restlerHtmlFile = function(Url) {
  rest.get(Url).on('complete', function(result) {
   fs.writeFileSync('file.html',result);
  });
};

if(require.main == module) {
  restlerHtmlFile('http://obscure-refuge-7370.herokuapp.com/');
  fs.readFileSync('file.html');
}

to

var restlerHtmlFile = function(Url) {
  rest.get(Url).on('complete', function(result) {
   fs.writeFileSync('file.html',result);
   fs.readFileSync('file.html');
  });
};

if(require.main == module) {
  restlerHtmlFile('http://obscure-refuge-7370.herokuapp.com/');
}

Second parameter to rest.get(Url).on is an asynchronous call back function, which will be called when complete occurs and only then the file gets created. But you are reading the file, even before the complete occurs. Thats why you are getting this error.

Solution courtesy of: thefourtheye

Discussion

You don't write the file until the complete event fires, but you try to read from it immediately.

Since it doesn't yet exist, you get an exception, which you don't catch, so the program exits before the complete event fires and the file is written.

You need to move the code that tries to read from the file inside the event handler that writes the file.

Discussion courtesy of: Quentin

This recipe can be found in it's original form on Stack Over Flow.