最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to pass .json file name as argument to command line in node.js - Stack Overflow

programmeradmin0浏览0评论

I run app.js with mand 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 mand 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,

I run app.js with mand 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 mand 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,

Share Improve this question edited Nov 12, 2017 at 17:09 o.O asked Nov 12, 2017 at 17:04 o.Oo.O 5011 gold badge11 silver badges27 bronze badges 2
  • 1 you have process.argv to access cmdline arguments stackoverflow./a/4351548/3410584. Then simply require with the good index – ValLeNain Commented Nov 12, 2017 at 17:12
  • Possible duplicate of How do I pass mand line arguments? – insert_name_here Commented Nov 12, 2017 at 17:30
Add a ment  | 

1 Answer 1

Reset to default 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'));
发布评论

评论列表(0)

  1. 暂无评论