Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing csv file as command like argument in nodeJs

I can't for the life of me think of a way to do this. I've previously worked with importing csv files into js files, but for this challenge I've got to create a js file that executable from a shell with the data file passed as input.

Any ideas how can this be done?

~The challenge description~

The program must be executable from a shell and take the CSV file as input. For example:

node score_calculator.js data.csv
like image 699
alanionita Avatar asked Aug 06 '26 01:08

alanionita


2 Answers

You can take the file path as command line argument when running your nodejs app like

node myScript.js pathToCsvFile

Now you'll have to get this path in your code as

var filePath = process.argv[2];

Now you can use this path to read your file as

   fs.readFile(filePath, (err, data) => {
     if (err) throw err;
    console.log(data);
 });

Read more about file handling in nodejs here

Hope this helps

like image 141
Muhammad Usman Avatar answered Aug 07 '26 15:08

Muhammad Usman


Sounds like you are trying to figure out how to pass and read parameters

You could do node score_calculator.js data.csv

then in your js

const csv = process.argv[2];

However. If you are passing in parameters I would recommend using minimist then you can do

node score_calculator.js --file=data.csv

And you js file would be

const argv = require('minimist')(process.argv.slice(2));
const csv = argv.file;
like image 21
Sam Stephenson Avatar answered Aug 07 '26 16:08

Sam Stephenson