给定一个jsdom
基于svgcreator.node.js
脚本的文件:
var jsdom = require('jsdom'); jsdom.env( "", // 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) * * * * * * * * * * * * * * * * * * * * * * * * );
鉴于我使用NodeJS终端命令来运行它并生成一个output.svg
文件:
node svgcreator.node.js > output.svg # nodeJS + script command
如何将参数的值从终端传递给NodeJS?
测试的依赖性:
svgcreator.node.js github存储库: git clone 'git@github.com:hugolpz/svgcreator.node.js.git'
需要jsdom,使用:( sudo npm install -g jsdom
全局).
使用的解决方案(@Matt_Harrison):我们依赖process.env.myVar
svgcreator.node.js
JS代码:
var jsdom = require('jsdom'); jsdom.env( "", // 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) * * * * * * * * * * * * * * * * * * * * * * * * );
终端NodeJS命令:
COLOR=#66AAFF node svgcreator.node.js > out.svg # <<############# IMPORTANT !! setting the value.
+1 @Matt_Harrison回答并提出质疑!
在终端中,您可以使用环境变量:
$ 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以获得更全面的解决方案.