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

后端 未结 3 635
耶瑟儿~
耶瑟儿~ 2021-01-01 08:35

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 cre

相关标签:
3条回答
  • 2021-01-01 09:26

    Found the solution. fs.writeFileSync gets a third arguments for options that can be an object. So if you get the "File already exist" you should do.

    fs.writeFileSync(path,content,{encoding:'utf8',flag:'w'})
    
    0 讨论(0)
  • 2021-01-01 09:26

    When you say "best way", i think at performance and scalability and i'd say use the asynchronous method

    fs.writeFileSync(path,string) as the name suggest is synchronous (blocking api) the thread is held for the whole lifecycle of the request, that means your nodejs thread will be blocked until the operation finishes and this behavior in a production environment with simultaneous connections from multiple clients could kill your app.

    Do not think at the single line of code, less code doesn't mean better performance.

    0 讨论(0)
  • 2021-01-01 09:33

    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.

    0 讨论(0)
提交回复
热议问题