Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Read a text file using Node.js?

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?

Problem courtesy of: fancy


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 

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 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.

Solution courtesy of: maerics


View additional discussion.

This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Read a text file using Node.js?


Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription