gpt4 book ai didi

Node.js : how to pass JS variable's value from script to terminal?

转载 作者:太空宇宙 更新时间:2023-11-04 01:02:52 25 4
gpt4 key购买 nike

给定一个正在运行的 JS 脚本 a D3js dynamic dataviz

enter image description here

我目前使用以下方法将单个 View 打印到 output.svg 文件中:

<强> 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 MAP DRAWING CODE * * * * * * * * * * * * * * * * * * *
function (err, window) {

var svg = window.d3.select("body")
.append("svg") // append svg on body
... // more D3js code
// END svg design

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

终端 NodeJS 命令:

node svgcreator.node.js > output.svg

它的工作方式是,来自 svgcreator.node.js 脚本的每条 console.log() 消息都会打印到 output.svg 文件中。

自从这个 D3js dataviz 遍布全局,应该可以将每个 View 的一条 console.log() 消息打印到正确命名的正确 svg 文件中。我想我应该从 JS 脚本到终端获取一个变量,例如 varcountry=...;。然后,我可以做(?)这样的事情:

node svgcreator.node.js > $(JsVar.country).svg    # nb: this var syntax if fictional 

因此,每当收到 console.log() 消息时,该消息就会以正确的名称打印到 SVG 文件中。

另外,如何将 JS 变量的值从脚本传递到终端?

另请参阅:Node.js : how to pass parameter's value from terminal to JS script

最佳答案

最简单的方法是让 Node 直接写入文件,而不是尝试使用 > somefile.svg

执行此操作的代码非常简单。假设您的脚本中有一个名为 country 的变量,其中包含您要为其创建 .svg 的国家/地区的名称。不要使用 console.log 输出 .svg 文件,而是使用 fs.writeFileSync 将其写入 country + '.svg' .

所以,这个:

console.log(window.d3.select("body").html());

将更改为:

fs.writeFileSync(country + '.svg', window.d3.select("body").html());

注意:不要忘记 var fs = require('fs'); 访问 fs模块。

关于Node.js : how to pass JS variable's value from script to terminal?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25631104/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com