1

When I am trying to write in file data:

var data = "Hello"
fs.open(path, 'a', 0666, function(err, fd) {
  fs.writeSync(fd, data);
});

and it writes duplicate in file:

HelloHello

Why it writes the same twice?

  • I'm assuming that your code is in a function and the function is executing twice(Once on load and once when you call it). Can you provide more code, such as how you execute it? – Grice Dec 17 '14 at 14:39
  • Try this url: http://stackoverflow.com/questions/2496710/writing-files-in-node-js maybe in other variant its will work fine. another issue: try to console.log and see if its print twice to see exactly where to problem (the open func or wirtesSync – Menashe Yamin Dec 17 '14 at 14:41

1 Answers1

0

You're currently opening the file in append mode (that's what the 'a' stands for). This mode means any data you write will be appended to the END of the file.

So if you run this script twice, you'll see the results you're getting: HelloHello. If you delete your file then re-run the script one time, you'll see the correct results.

If you'd like to write this data only once, you should probably use the 'w' mode (write mode) -- this will write whatever you want into the file, destroying whatever was previously there.

rdegges
  • 32,786
  • 20
  • 85
  • 109
  • I need append my string to existing file. And I'm sure that this code runs only once, but in file it appears `HelloHello` instead of `Hello`. – Mykola Striletskyy Dec 18 '14 at 07:20