1

I'm simply trying to read a text file in Node. I'm not in the DOM.

I can write to a file with this package but I'm having trouble reading from it .

I know i neead the following:

var fs = require('fs');
var readStream = fs.createReadStream('my_file.txt');

But the readStream is a complex object. I just want the variable as a string. Any ideas?

asked Apr 29, 2015 at 22:19
0

1 Answer 1

3

If it's a file, why wouldn't you use fs.readFile, which was intended for reading files

fs.readFile('my_file.txt', {encoding : 'utf8'}, function (err, data) {
 if (err) throw err;
 var fileContent = data;
});

There's even a synchronous version available, which you generally shouldn't be using

var fileContent = fs.readFileSync('my_file.txt', {encoding : 'utf8'});
answered Apr 29, 2015 at 22:22
Sign up to request clarification or add additional context in comments.

1 Comment

It should be noted that if you plan on reading several files at the same time (e.g. in response to a request), you may get better leverage using fs.createReadStream(...) and processing the file using the streaming API. Although more convenient, fs.readFile() will buffer the entire file in memory.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.