【问题标题】:How to pass .json file name as argument to command line in node.js如何将 .json 文件名作为参数传递给 node.js 中的命令行
【发布时间】:2017-11-12 17:04:07
【问题描述】:

我使用命令 node app.js 运行 app.js

它执行const inputData = require('./input.json');

是否可以从命令行将文件名作为参数传递给const inputData = require('./file.json');?我的意思是:

node app.js file.json

我对这个诡计完全陌生,没有理论意义。我应该从哪里开始?非常感谢所有可能的帮助。

非常感谢,

【问题讨论】:

标签: javascript json node.js terminal


【解决方案1】:

您可以使用process.argv 访问参数,并使用fs.readFilefs.readFileSync 读取文件内容。

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

【讨论】:

  • 为什么我不能将console.log(fileName, fs.readFileSync(fileName, 'utf-8')); 放入const
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-05-20
  • 2017-12-17
相关资源
最近更新 更多