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?
Asked
Active
Viewed 313 times
0
-
What code do you have so far? – Sumner Evans Dec 10 '13 at 21:07
-
2`filedata = require('fs').readFileSync(filename);` will do. – Leonid Beschastny Dec 10 '13 at 21:07
-
See answer in this SO question: http://stackoverflow.com/questions/19918326/how-do-you-read-a-file-or-stream-synchronously-in-node-js – user949300 Dec 10 '13 at 21:08
2 Answers
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