Rabbitshoe
Rabbitshoe

Reputation: 77

Reading a file in Javascript in Node

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?

Upvotes: 1

Views: 87

Answers (1)

adeneo
adeneo

Reputation: 318342

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'});

Upvotes: 3

Related Questions