3

On the command line, if I run

echo -n "foo" | openssl aes-128-cbc -k "key" -base64 -e

(the -n flag prevents echo from adding a newline to the end of its output), I get

U2FsdGVkX1+nMW5I4eZSasPKfsUuCpbFsnn56ngEdec=

But when I run

exec = require('child_process').exec;
exec('echo -n "foo" | openssl aes-128-cbc -k "key" -base64 -e', callback);

the callback gets the output

U2FsdGVkX1/CARBiGos0x9ALNhFqcIaFvZ9EUvVBxuc=

Why is it different? Decrypt it, and you'll get the string

-n foo

So somehow, exec encoded -n "foo" into "-n foo" (under Node 0.4.2).

Here's the weirdest part: I don't get this problem when I run my code directly from TextMate (via jashkenas' CoffeeScript bundle). At first I thought it was a path issue, but it isn't (making PATH identical in the two environments had no effect). Perhaps it's because one environment is a TTY and one isn't.

Are other folks aware of this inconsistency? Is this a Node bug, or am I ignoring something? I'm guessing that my problems will go away if I use the lower-level spawn instead of exec.

Trevor Burnham
  • 76,828
  • 33
  • 160
  • 196

1 Answers1

3

Perhaps your /bin/echo doesn't respect -n? echo is frequently a shell builtin, and that one may respect -n. You may wish to use printf(1) instead, it is more portable.

sarnold
  • 102,305
  • 22
  • 181
  • 238
  • Hmm, `/bin/echo -n "foo"` seems to work as expected on the shell, so I still think the root cause is a problem with Node's `exec`. Thanks for the `printf` pointer, though—I was able to fix the problem with it. – Trevor Burnham Mar 19 '11 at 13:58
  • Trevor Burnham, if you figure out the root cause of your problem, I'd really like to know why your initial code didn't work as expected. But I'm glad you found a workaround that gets the job done. – sarnold Mar 20 '11 at 23:57
  • 2
    I just ran into this myself. Could it be that Node is using /bin/sh rather than /bin/bash? From echo's man page: "Most notably, the builtin echo in sh(1) does not accept the -n option." In my case I simulated `echo -n` with `echo foo | tr -d '\n'`. – davidchambers Feb 24 '13 at 20:31