Node.js : how to pass parameter's value from t

2019-04-01 00:20发布

Given a jsdom based svgcreator.node.js script file :

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

Given I use NodeJS terminal command to run it and generate a output.svg file :

node svgcreator.node.js > output.svg  # nodeJS + script command

How to pass a parameter's value from the terminal to NodeJS ?


Dependencies for tests:


Solution used (@Matt_Harrison): we rely on process.env.myVar

svgcreator.node.js JS code :

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

Terminal NodeJS command :

COLOR=#66AAFF node svgcreator.node.js > out.svg   # <<############# IMPORTANT !! setting the value.

+1 @Matt_Harrison answer and the question appreciated !

标签: node.js svg
1条回答
何必那么认真
2楼-- · 2019-04-01 01:04

In your terminal, you can use environment variables:

$ COLOR=#FFFFFF node jsdom.node.js

In your JS, do:

var color = process.env.COLOR;

Or you could add extra arguments to the command:

$ node jsdom.node.js '#FFFFFF'

and in your JS :

var color = process.argv[2];

If you want to use a library; I would advise looking into the Minimist library, or Commander for a more fully-featured solution.

查看更多
登录 后发表回答