[javascript] Read a text file using Node.js?

I need to pass in a text file in the terminal and then read the data from it, how can I do this?

node server.js file.txt

How do I pass in the path from the terminal, how do I read that on the other side?

This question is related to javascript node.js

The answer is


The async way of life:

#! /usr/bin/node

const fs = require('fs');

function readall (stream)
{
  return new Promise ((resolve, reject) => {
    const chunks = [];
    stream.on ('error', (error) => reject (error));
    stream.on ('data',  (chunk) => chunk && chunks.push (chunk));
    stream.on ('end',   ()      => resolve (Buffer.concat (chunks)));
  });
}

function readfile (filename)
{
  return readall (fs.createReadStream (filename));
}

(async () => {
  let content = await readfile ('/etc/ssh/moduli').catch ((e) => {})
  if (content)
    console.log ("size:", content.length,
                 "head:", content.slice (0, 46).toString ());
})();

IMHO, fs.readFile() should be avoided because it loads ALL the file in memory and it won't call the callback until all the file has been read.

The easiest way to read a text file is to read it line by line. I recommend a BufferedReader:

new BufferedReader ("file", { encoding: "utf8" })
    .on ("error", function (error){
        console.log ("error: " + error);
    })
    .on ("line", function (line){
        console.log ("line: " + line);
    })
    .on ("end", function (){
        console.log ("EOF");
    })
    .read ();

For complex data structures like .properties or json files you need to use a parser (internally it should also use a buffered reader).


You can use readstream and pipe to read the file line by line without read all the file into memory one time.

var fs = require('fs'),
    es = require('event-stream'),
    os = require('os');

var s = fs.createReadStream(path)
    .pipe(es.split())
    .pipe(es.mapSync(function(line) {
        //pause the readstream
        s.pause();
        console.log("line:", line);
        s.resume();
    })
    .on('error', function(err) {
        console.log('Error:', err);
    })
    .on('end', function() {
        console.log('Finish reading.');
    })
);

Usign fs with node.

var fs = require('fs');

try {  
    var data = fs.readFileSync('file.txt', 'utf8');
    console.log(data.toString());    
} catch(e) {
    console.log('Error:', e.stack);
}

I am posting a complete example which I finally got working. Here I am reading in a file rooms/rooms.txt from a script rooms/rooms.js

var fs = require('fs');
var path = require('path');
var readStream = fs.createReadStream(path.join(__dirname, '../rooms') + '/rooms.txt', 'utf8');
let data = ''
readStream.on('data', function(chunk) {
    data += chunk;
}).on('end', function() {
    console.log(data);
});