0

I've been trying to build a small bash script to override some configuration in Node. I'm using zsh, so there's a warning if you redirect output in an existing file (see here). I've been trying the proposed answer, although the output is quite unusual. I was wondering maybe I'm doing something wrong here.

echo 'module.exports = { "foo": 1 }' > foo.js

node -e '
  const foo = require("./foo")
  foo.bar = 1
  console.log(`module.exports = ${JSON.stringify(foo)}`)
'

# output is: module.exports = {"foo":1,"bar":1}

node -e '
  const foo = require("./foo")
  foo.bar = 1
  console.log(`module.exports = ${JSON.stringify(foo)}`)
' > bar.js

cat bar.js

# output is: module.exports = {"foo":1,"bar":1}

node -e '
  const foo = require("./foo")
  foo.bar = 1
  console.log(`module.exports = ${JSON.stringify(foo)}`)
' >| foo.js

# output is: module.exports = {"bar":1}

I was under the impression that >| would bypass the "overwrite file" warning from zsh, but it does compute a "different than expected" return value.

Actual: module.exports = {"bar":1}
Expected: module.exports = {"foo":1,"bar":1}

Where have gone the bytes of "foo:1"? Could somebody explain me what's happening?

2
  • 2
    What is the issue? Could you point out what you think is unusual? Also, are you using bash or zsh (you mention both)? Note that redirections are carried out before the command is executed. If the redirection truncates the file, it is truncated when the command runs.
    – Kusalananda
    Jun 14, 2020 at 9:36
  • @Kusalananda i'm sorry if i didn't make the outcome clear enough. let me edit/add some expectations there so you get a better understanding
    – y_nk
    Jun 15, 2020 at 11:59

1 Answer 1

3

When the output of a command is redirected with > or >| to a file, that file is first truncated (emptied), then the command is executed.

When you run your Node.js code in the last example, the file foo.js is empty, due to to redirection. This is why the original data from that file is not visible in the output.

1
  • that makes a lot of sense! thank you :)
    – y_nk
    Jun 16, 2020 at 17:14

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .