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?

3
  • What code do you have so far? Commented Dec 10, 2013 at 21:07
  • 2
    filedata = require('fs').readFileSync(filename); will do. Commented Dec 10, 2013 at 21:07
  • See answer in this SO question: stackoverflow.com/questions/19918326/… Commented Dec 10, 2013 at 21:08

2 Answers 2

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);
}
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.