Read a Text File Using Node.Js

Read a text file using Node.js?

You'll want to use the process.argv array to access the command-line arguments to get the filename and the FileSystem module (fs) to read the file. For example:

// Make sure we got a filename on the command line.
if (process.argv.length < 3) {
console.log('Usage: node ' + process.argv[1] + ' FILENAME');
process.exit(1);
}
// Read the file and print its contents.
var fs = require('fs')
, filename = process.argv[2];
fs.readFile(filename, 'utf8', function(err, data) {
if (err) throw err;
console.log('OK: ' + filename);
console.log(data)
});

To break that down a little for you process.argv will usually have length two, the zeroth item being the "node" interpreter and the first being the script that node is currently running, items after that were passed on the command line. Once you've pulled a filename from argv then you can use the filesystem functions to read the file and do whatever you want with its contents. Sample usage would look like this:

$ node ./cat.js file.txt
OK: file.txt
This is file.txt!

[Edit] As @wtfcoder mentions, using the "fs.readFile()" method might not be the best idea because it will buffer the entire contents of the file before yielding it to the callback function. This buffering could potentially use lots of memory but, more importantly, it does not take advantage of one of the core features of node.js - asynchronous, evented I/O.

The "node" way to process a large file (or any file, really) would be to use fs.read() and process each available chunk as it is available from the operating system. However, reading the file as such requires you to do your own (possibly) incremental parsing/processing of the file and some amount of buffering might be inevitable.

node.js: read a text file into an array. (Each line an item in the array.)

If you can fit the final data into an array then wouldn't you also be able to fit it in a string and split it, as has been suggested?
In any case if you would like to process the file one line at a time you can also try something like this:

var fs = require('fs');

function readLines(input, func) {
var remaining = '';

input.on('data', function(data) {
remaining += data;
var index = remaining.indexOf('\n');
while (index > -1) {
var line = remaining.substring(0, index);
remaining = remaining.substring(index + 1);
func(line);
index = remaining.indexOf('\n');
}
});

input.on('end', function() {
if (remaining.length > 0) {
func(remaining);
}
});
}

function func(data) {
console.log('Line: ' + data);
}

var input = fs.createReadStream('lines.txt');
readLines(input, func);

EDIT: (in response to comment by phopkins) I think (at least in newer versions) substring does not copy data but creates a special SlicedString object (from a quick glance at the v8 source code). In any case here is a modification that avoids the mentioned substring (tested on a file several megabytes worth of "All work and no play makes Jack a dull boy"):

function readLines(input, func) {
var remaining = '';

input.on('data', function(data) {
remaining += data;
var index = remaining.indexOf('\n');
var last = 0;
while (index > -1) {
var line = remaining.substring(last, index);
last = index + 1;
func(line);
index = remaining.indexOf('\n', last);
}

remaining = remaining.substring(last);
});

input.on('end', function() {
if (remaining.length > 0) {
func(remaining);
}
});
}

Read text file using node js

You can use readline from node.js. Here is the code you can use:

const readline = require('readline');
const fs = require('fs');

async function readFile(filePath) {
const myInterface = readline.createInterface({ input: fs.createReadStream(filePath)});
const arrayLink = [],
arrayName = [];

for await (const line of myInterface) {
let temp = line.split(",");
arrayLink.push(temp[0]);
arrayName.push(temp[1]);
}
console.log(arrayLink, arrayName);
}
readFile(filePath)

This Updated code will run the way you are expecting. Check this one.

Read a file one line at a time in node.js?

Since Node.js v0.12 and as of Node.js v4.0.0, there is a stable readline core module. Here's the easiest way to read lines from a file, without any external modules:

const fs = require('fs');
const readline = require('readline');

async function processLineByLine() {
const fileStream = fs.createReadStream('input.txt');

const rl = readline.createInterface({
input: fileStream,
crlfDelay: Infinity
});
// Note: we use the crlfDelay option to recognize all instances of CR LF
// ('\r\n') in input.txt as a single line break.

for await (const line of rl) {
// Each line in input.txt will be successively available here as `line`.
console.log(`Line from file: ${line}`);
}
}

processLineByLine();

Or alternatively:

var lineReader = require('readline').createInterface({
input: require('fs').createReadStream('file.in')
});

lineReader.on('line', function (line) {
console.log('Line from file:', line);
});

The last line is read correctly (as of Node v0.12 or later), even if there is no final \n.

UPDATE: this example has been added to Node's API official documentation.

How can I use node.js to read a text file of nouns and store it in a variable

Assuming files look like:

noun
noun1

You can load this in as such. This is in a synchronous way. You could also do this in an asynchronous way if desired.

const fs = require("fs");
const nounFile = "nouns.txt";
const verbFile = "verbs.txt";

const readFile = function (file) {
return fs.readFileSync(file).toString().split("\n");
};

const randomItem = function (items) {
return items[Math.floor(Math.random() * items.length)];
};

const nouns = readFile(nounFile);
const verbs = readFile(verbFile);
const noun = randomItem(nouns);
const verb = randomItem(verbs);

Is there a way to read a text file synchronously (in JS node)?

You can use the readFileSync function for this:

    const data = fs.readFileSync('words_alpha_sorted.txt');

But the async functions are almost always a better solution. The sync methods stop Javascript execution for an unknown (compared to the JS code it seems like an eternity) amount of time, while the async filesystem functions are running in parallel.

You can take advantage of the async/await-friendly Promise methods to do:

var dicWords = []
async function ReadFile()
{
var fs = require('fs').promises
let data = await fs.readFile('words_alpha_sorted.txt')
data = String(data)
dicWords = data.split(/\r?\n/);
}
function DoStuffWithFile();
{
//do stuff with the variable dicWords
}
async function main()
{
await ReadFile();
DoStuffWithFile();
}


Related Topics



Leave a reply



Submit