有没有一种方法可以将所有控制台语句记录到节点中的文件中。
我最近正在从事一个小型项目,想了解如何运行cli命令并将其输出保存到文件中。
例如:node -v
将v9.7.1
在终端上输出。我如何从文件执行它并记下它的输出?我尝试将相同的命令放入JS文件中并运行,node test.js
但是它返回以下错误。
/home/kashyap/Documents/Code/testgits/1.js:1
(function (exports, require, module, __filename, __dirname) { node -v
^
ReferenceError: node is not defined
at Object.<anonymous> (/home/kashyap/Documents/Code/testgits/1.js:1:63)
at Module._compile (module.js:662:30)
at Object.Module._extensions..js (module.js:673:10)
at Module.load (module.js:575:32)
at tryModuleLoad (module.js:515:12)
at Function.Module._load (module.js:507:3)
at Function.Module.runMain (module.js:703:10)
at startup (bootstrap_node.js:193:16)
at bootstrap_node.js:660:3
我如何在文件中运行控制台命令。类似于编写脚本吗?
您可以使用child_process
模块
const spawn = require('child_process');
spawn.exec('node -v', (err, stdout, stderr) => {
if (err) {
return;
}
console.log(`stdout: ${stdout}`);
});
标准输出:v8.9.4
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句