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

标签 node.js

当我在 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/

相关文章:

node.js - Post请求在flutter应用程序中发送未定义的数据

node.js - 如何在 Node.js 中从 Redis 客户端使用 SINTERSTORE 和 ZINTERSTORE?

node.js - 需要 ('https' )与需要 ('tls' )

node.js - 如何连接和运行 Node.js 和 React Native?

node.js - 仅套接字 IO session 不持久

javascript - 回调问题

node.js - 如何获取上传文件的文件路径以创建ReadStream

node.js - 复合 JS 中的模板引擎

node.js - 在nodejs中同步递归调用函数

node.js - winston + PM2 记录 uncaughtException 两次