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

Viewed 4647

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,

1 Answers

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'));
Related