gpt4 book ai didi

node.js - echo 忽略 child_process.exec() 中的标志

转载 作者:搜寻专家 更新时间:2023-11-01 00:32:13 26 4
gpt4 key购买 nike

当我在 bash 中直接键入 echo -n foo 时,它按预期工作并打印 foo 而没有任何尾随换行符。

但是,我已经编写了以下代码来使用 child_process.exec() 方法打印一些文本;

var exec = require('child_process').exec;
exec("echo -n foo",
function(error, stdout, stderr) {
console.log(stdout);
}
);

但是,-n 标志没有按预期工作,它打印 -n foo 后跟一个空行。

更新:我发现问题只发生在 OS X 上,我在 Ubuntu 上尝试了相同的脚本,它按预期工作。

最佳答案

在 Linux 上至少使用 node v0.10.30 对我来说工作正常。

这个:

var exec = require('child_process').exec;
exec('echo -n foo', function(error, stdout, stderr) {
console.dir(stdout);
});

输出:

'foo'

However, on Windows the behavior you describe does exist, but that is because Windows' echo command is not the same as on *nix (and so it echoes exactly what came after the command).

The reason it also does not work on OS X is because (from man echo):

     Some shells may provide a builtin echo command which is similar or iden-     tical to this utility.  Most notably, the builtin echo in sh(1) does not     accept the -n option.

When you call exec(), node spawns /bin/sh -c "<command string>" on *nix platforms. So (as noted in the man page) /bin/sh on OS X does not support echo -n, which results in the output you're seeing. However it works from the terminal because the default shell for that user is not /bin/sh but likely /bin/bash, which does support echo -n. It also works on Linux because most systems have /bin/sh pointing to /bin/bash or some other shell that supports echo -n.

So the solution is to change the command to force the use of the echo binary instead of the built-in shell's echo:

var exec = require('child_process').exec;
exec('`which echo` -n foo', function(error, stdout, stderr) {
console.dir(stdout);
});

或使用 spawn() 像这样:

var spawn = require('child_process').spawn,
p = spawn('echo', ['-n', 'foo']),
stdout = '';
p.stdout.on('data', function(d) { stdout += d; });
p.stderr.resume();
p.on('close', function() {
console.dir(stdout);
});

或者如果您想继续使用 exec()不更改代码,然后制作/bin/sh /bin/bash 的符号链接(symbolic link).

关于node.js - echo 忽略 child_process.exec() 中的标志,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26898490/

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