Node.js:如何将参数值从终端传递给JS脚本

时间:2014-08-09 15:45:26

标签: node.js svg

根据基于jsdom的{​​{1}}脚本文件:

svgcreator.node.js

鉴于我使用NodeJS终端命令运行它并生成var jsdom = require('jsdom'); jsdom.env( "<html><body></body></html>", // CREATE DOM HOOK [ 'http://d3js.org/d3.v3.min.js', // JS DEPENDENCIES online ... 'js/d3.v3.min.js' ], // ... & offline // D3JS CODE * * * * * * * * * * * * * * * * * * * * * * * * function (err, window) { var svg = window.d3.select("body") .append("svg") .attr("width", 100) .attr("height", 100); svg.append("rect") .attr("id", "rect1") .attr("x", 10) .attr("y", 10) .attr("width", 80) .attr("height", 80) .style("fill", "green"); // END svg design //PRINTING OUT SELECTION console.log(window.d3.select("body").html()); } // END (D3JS) * * * * * * * * * * * * * * * * * * * * * * * * ); 文件:

output.svg

如何将参数的值从终端传递给NodeJS?


测试的依赖关系:

  • svgcreator.node.js github repositorynode svgcreator.node.js > output.svg # nodeJS + script command
  • jsdom required,使用:git clone 'git@github.com:hugolpz/svgcreator.node.js.git'(全局)。

使用的解决方案(@Matt_Harrison):我们依赖于sudo npm install -g jsdom

process.env.myVar JS代码:

svgcreator.node.js

终端NodeJS命令:

var jsdom = require('jsdom');
jsdom.env(
  "<html><body></body></html>",        // CREATE DOM HOOK:
  [ 'http://d3js.org/d3.v3.min.js',    // JS DEPENDENCIES online ...
  'js/d3.v3.min.js' ],                 // ... & offline
// D3JS CODE * * * * * * * * * * * * * * * * * * * * * * * *
  function (err, window) {

    var color = process.env.COLOR;     // <<################# IMPORTANT !!
    var svg = window.d3.select("body")
        .append("svg")
        .attr("width", 100)
        .attr("height", 100);
    svg.append("rect")
        .attr("id", "rect1")
        .attr("x", 10)
        .attr("y", 10)
        .attr("width", 80)
        .attr("height", 80)
        .style("fill", color);         // <<################# IMPORTANT !!
    // END svg design

  //PRINTING OUT SELECTION
    console.log(window.d3.select("body").html());
 }
// END (D3JS) * * * * * * * * * * * * * * * * * * * * * * * *
);

+1 @Matt_Harrison回答并提出质疑!

1 个答案:

答案 0 :(得分:15)

在您的终端中,您可以使用environment variables

$ COLOR=#FFFFFF node jsdom.node.js

在你的JS中,执行:

var color = process.env.COLOR;

或者您可以为命令添加额外的参数:

$ node jsdom.node.js '#FFFFFF'

并在你的JS中:

var color = process.argv[2];

如果你想使用图书馆;我建议您查看Minimist库或Commander以获得功能更全面的解决方案。