0
votes

I am currently writing JSON to a file, which I pipe to a shell command:

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

Rather than writing to a file, how can I safely print/pass this to my binary_file through Node?

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

Is there some way to safely escape strings for shell execution, or is there a better way to accomplish this?

Or, is writing/reading a file any safer?

1
What does the binary file do?l'L'l
It reads from STDIN and expects JSON string, but curious why that matters?d-_-b

1 Answers

1
votes

A shell won't mangle your data if you don't run 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();