o.O
o.O

Reputation: 501

How to pass .json file name as argument to command line in node.js

I run app.js with command node app.js

It executes const inputData = require('./input.json');

Is it possible pass file name as argument to const inputData = require('./file.json'); from command line? I mean:

node app.js file.json

I am totally new to this trickery, have no theoretical point. From where I should start? Many thanks for all possible help.

Much obliged,

Upvotes: 3

Views: 5863

Answers (1)

Pedro Rodrigues
Pedro Rodrigues

Reputation: 1688

You can use the process.argv to access arguments, and fs.readFile or fs.readFileSync to read file content.

const fs = require('fs');

// Non-blocking example with fs.readFile
const fileNames = process.argv.splice(2);

fileNames.forEach(fileName => {
    fs.readFile(fileName, 'utf-8', (error, data) => {
        if (error) throw error;
        console.log(fileName, data);
  });
});

// Blocking example with fs.readFileSync
const fileName = fileNames[0];
console.log(fileName, fs.readFileSync(fileName, 'utf-8'));

Upvotes: 5

Related Questions