0

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?

2
  • What does the binary file do? Commented Aug 15, 2018 at 19:23
  • It reads from STDIN and expects JSON string, but curious why that matters? Commented Aug 15, 2018 at 19:27

1 Answer 1

1

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();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.