1

I'm playing with Node.js fs.writeFile() flags to find the right file for my problem: I want to replace the content of a file but throw an error if the file does not exist.

My first try was with r+ but I have issues if the new content is shorter than the old one:

fs.writeFileSync('test', '11111111111');
> 111111111111
fs.writeFileSync('test', '22', {flag: 'r+'})
> 221111111111

Removing the flag solve the problem (give 22) but create a new file if test doesn't exist.

Is it doable with a flag or do I need to detect file existence before (not very found of that)?

1 Answer 1

2

You can't do this in a single step: opening a file for writing will create the file if it does not exist, while opening the file with r+ mode presents the problem you mention.

I see two options:

  1. Test for existence using fs.stat(), then fs.writeFile() in w mode.
  2. Open the file in r+ mode, write to it, then fs.ftruncate() the file to the desired size.

I recommend the first approach. The code will be easier to read and reason about.

Sign up to request clarification or add additional context in comments.

2 Comments

I was always told testing the file before is an anti-pattern because it won't guarantee the file status when you'll write. I may have concurrent access on this file so isn't the 2nd better? Thank you
Since I want to override the file, I found out the best method is indeed delete it, watch for error (if it doesn't exist), then write it with default flag. Thank you

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.