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?
1 Answer 1
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
adeneo
319k29 gold badges410 silver badges392 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
ctt
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.lang-js