【问题标题】:How to use node.js to access arguments from a .json file instead of command line?如何使用 node.js 从 .json 文件而不是命令行访问参数?
【发布时间】:2016-05-10 23:12:02
【问题描述】:

This SO answer describes use of the process.argv variable to access command line arguments when using node.js to run a javascript file.

Here is the source documentation for process.argv.

但是,如果我的参数存储在 .json 文件中,而不是在命令行中单独输入,该怎么办。有没有办法也可以使用 node.js 访问它们?

数据.json
{ 
  "foo": "bar",
  "baz": "bat"
}

我想以某种方式将 data.json 作为参数加载到我也本地存储在计算机上的 .js 文件中。然后运行它。

应用程序.js
var foo = "bar",
    baz = "bat"; // Somehow, I need to import these arguments from data.json
// Then do stuff with them...

【问题讨论】:

    标签: javascript node.js command-line


    【解决方案1】:

    您可以要求您的 json 文件,并将您的本地值设置为所需的值。

    代码会是这样的:

    var params = require('./data.json');
    var foo = params.foo;
    var bac = params.baz;
    

    【讨论】:

      【解决方案2】:

      你可以:

      var json = require('youjsonfile.json');
      
      var foo = json.foo;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-01-19
        • 2011-06-25
        • 1970-01-01
        • 2011-05-15
        • 1970-01-01
        相关资源
        最近更新 更多