![](/img/trans.png)
[英]How to use node.js to access arguments from a .json file instead of command line?
[英]How to pass .json file name as argument to command line in node.js
我用命令node app.js
运行node app.js
它执行const inputData = require('./input.json');
是否可以将文件名作为参数传递给const inputData = require('./file.json');
从命令行? 我的意思是:
node app.js file.json
我对这个诡计完全不熟悉,没有理论观点。 我应该从哪里开始? 非常感谢所有可能的帮助。
多谢,
您可以使用process.argv访问参数,使用fs.readFile或fs.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'));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.