从文件中运行命令行命令

时间:2021-05-18 01:01:55

Is there was a way to log all console statements to a file in node.

是否有一种方法可以将所有控制台语句记录到节点中的一个文件中。

I was recently working on a mini project and wanted to find out how to run cli commands and save it's output to a file.

我最近在做一个小型项目,想知道如何运行cli命令并将输出保存到文件中。

For ex: node -v would output v9.7.1 on the terminal. How do i execute it from a file and note down it's output? I tried putting the same command in a JS file and running node test.js but it returned the following error.

对于例:节点-v将在终端上输出v9.7.1。如何从文件中执行它,并记下它的输出?我尝试在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

How do i run console commands in a file. Similar to writing a script?

如何在文件中运行控制台命令。类似于写剧本?

1 个解决方案

#1


2  

You can use the child_process module

您可以使用child_process模块

const spawn = require('child_process');

spawn.exec('node -v', (err, stdout, stderr) => {
    if (err) {
        return;
    }
    console.log(`stdout: ${stdout}`);
});

stdout: v8.9.4

stdout:v8.9.4

#1


2  

You can use the child_process module

您可以使用child_process模块

const spawn = require('child_process');

spawn.exec('node -v', (err, stdout, stderr) => {
    if (err) {
        return;
    }
    console.log(`stdout: ${stdout}`);
});

stdout: v8.9.4

stdout:v8.9.4