节点:转义 JSON 字符串以在 shell exec 中使用

Node: Escape JSON string to use in shell exec

我目前正在将 JSON 写入一个文件,我将其通过管道传输到 shell 命令:

const { exec } = require('child_process');
fs.writeFileSync('file.json', JSON.stringify(data), 'utf8');
exec(`cat file.json | ./binary_file`, {}, callback);

我如何才能通过 Node 安全地将此 binary_file binary_file binary_file 写入文件?

const { exec } = require('child_process');
exec(`echo '${JSON.stringify(data)}' | ./binary_file`, {}, callback);

是否有某种方法可以安全地转义字符串以执行 shell,或者是否有更好的方法来完成此操作?

或者,writing/reading 文件更安全吗?

A shell 如果你不 运行 A shell:

就不会破坏你的数据
const { spawn } = require('child_process');
const p = spawn('/path/to/your_executable');

// Write arbitrary data on stdin instead of
// passing it through a shell to have echo do it
p.stdin.write("{!`$)(*%]");

// Make sure to close stdin afterwards
p.stdin.end();