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:
git clone '[email protected]:hugolpz/svgcreator.node.js.git'
sudo npm install -g jsdom (global).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 !
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With