0

I am trying to read a file in node.js but I am getting tired of writing so many callbacks. Is there a way I can just read a file in one line?

2 Answers2

2

If you're just loading a config or a template you can use the sync read method

var my fileData = fs.readFileSync('myFileName');

If you need you do it as a reply to an http request you can use the streaming API

function (req, res) {
  fs.createReadStream('myFileName').pipe(res);
}
generalhenry
  • 17,227
  • 4
  • 48
  • 63
0

Callbacks are king, but you can use anonymous callbacks...

fs.readFile('/etc/passwd', function (err, data) {
    if (err) throw err;
    console.log(data);
});

http://nodejs.org/api/fs.html#fs_fs_readfile_filename_options_callback

Lou
  • 317
  • 1
  • 4