Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
142 views
in Technique[技术] by (71.8m points)

javascript - What's the best way to overwrite a file using fs in node.js

I'm trying to overwrite an existing file. I'm first checking if the file exists using:

fs.existsSync(path)

If file does not exit I'm creating and writing using:

fs.writeFileSync(path,string) 

The problem is when the file already exists and I want to over write all its contents. Is there a single line solution, so far I searched and found solutions that use fs.truncate & fs.write, but is there a one hit solution?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

fs.writeFileSync and fs.writeFile overwrite the file by default, there is no need for extra checks if this is what you want to do. This is mentioned in the docs:

fs.writeFile

Asynchronously writes data to a file, replacing the file if it already exists.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...