如何使用“>”在 Node.js 中重定向输出?

del*_*ber 5 javascript linux node.js

例如假设我想复制简单的命令

echo testing > temp.txt
Run Code Online (Sandbox Code Playgroud)

这是我尝试过的

var util  = require('util'),
    spawn = require('child_process').spawn;

var cat = spawn('echo', ['> temp.txt']);
cat.stdin.write("testing");
cat.stdin.end();
Run Code Online (Sandbox Code Playgroud)

可惜没有成功

mih*_*hai 5

您不能将重定向字符 (>) 作为参数传递给 spawn,因为它不是命令的有效参数。您可以使用exec代替 spawn,它会执行您在单独的 shell 中提供的任何命令字符串,或者采用以下方法:

var cat = spawn('echo', ['testing']);

cat.stdout.on('data', function(data) {
    fs.writeFile('temp.txt', data, function (err) {
        if (err) throw err;
    });
});
Run Code Online (Sandbox Code Playgroud)