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,

2

1 Answer 1

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'));
Sign up to request clarification or add additional context in comments.

1 Comment

Why I can't put console.log(fileName, fs.readFileSync(fileName, 'utf-8')); into const?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.