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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You’ll want to use the
process.argvarray to access the command-line arguments to get the filename and the FileSystem module (fs) to read the file. For example:To break that down a little for you
process.argvwill 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:[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.