假设有一个基于jsdom
的svgcreator.node.js
脚本文件:
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) * * * * * * * * * * * * * * * * * * * * * * * *
);
假设我使用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
(全局安装)。
Solution used (@Matt_Harrison): 我们依赖于 process.env.myVar < p >
svgcreator.node.js
JS 代码:
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) * * * * * * * * * * * * * * * * * * * * * * * *
);
终端NodeJS命令:
COLOR=#66AAFF node svgcreator.node.js > out.svg # <<############# IMPORTANT !! setting the value.
+1 @Matt_Harrison 的回答和问题都很赞赏!
jsdom.node.js
,该脚本在 nodejs JS 引擎 中运行。 - Hugolpz