使用nodejs将javascript变量传递给shell命令

dan*_*ler 5 javascript bash shell node.js

我正在使用nodejs应用程序,我需要将多行字符串传递给shell命令.我不是shell脚本的专家,但是如果我在我的终端中运行这个命令就可以了:

$((cat $filePath) | dayone new)

这是我为nodejs方面所做的.dayone命令确实有效,但没有任何信息传输到它.

const cp = require('child_process');
const terminal = cp.spawn('bash');

var multiLineVariable = 'Multi\nline\nstring';

terminal.stdin.write('mul');
cp.exec('dayone new', (error, stdout, stderr) => {
    console.log(error, stdout, stderr);
});
terminal.stdin.end();
Run Code Online (Sandbox Code Playgroud)

谢谢你的帮助!

Lee*_*all 5

在这里,您使用spawn 启动bash,然后使用exec 启动dayone 程序。它们是单独的子进程并且不以任何方式连接。

'cp'只是对child_process模块​​的引用,spawn和exec只是启动子进程的两种不同方式。

您可以使用 bash 并将 dayone 命令写入 stdin 以调用 dayone (正如您的代码片段似乎正在尝试执行的那样),或者您可以直接使用 exec 调用 dayone (请记住 exec 仍然在 shell 中运行该命令) :

var multiLineVariable = 'Multi\nline\nstring';

// get the child_process module
const cp = require('child_process');

// open a child process
var process = cp.exec('dayone new', (error, stdout, stderr) => {
    console.log(error, stdout, stderr);
});

// write your multiline variable to the child process
process.stdin.write(multiLineVariable);
process.stdin.end();
Run Code Online (Sandbox Code Playgroud)

  • exec 命令不会等待 dayone 完成/退出,因为 node.js 中没有任何内容会阻塞。Exec 只是启动进程,然后进程尝试从 stdin 读取数据。如果没有可用的东西,它将阻塞,直到有东西为止,当我们开始该过程时,我们就会立即提供它。就像您从命令行手动运行它一样,它会阻塞,直到您在其标准输入中输入一些内容。 (2认同)