3

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,

o.O
  • 491
  • 1
  • 10
  • 26
  • 1
    you have `process.argv` to access cmdline arguments https://stackoverflow.com/a/4351548/3410584. Then simply `require` with the good index – ValLeNain Nov 12 '17 at 17:12
  • Possible duplicate of [How do I pass command line arguments?](https://stackoverflow.com/questions/4351521/how-do-i-pass-command-line-arguments) – insert_name_here Nov 12 '17 at 17:30

1 Answers1

5

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'));
Pedro Rodrigues
  • 1,662
  • 15
  • 19
  • Why I can't put `console.log(fileName, fs.readFileSync(fileName, 'utf-8'));` into `const`? – o.O Nov 12 '17 at 17:50