-
Notifications
You must be signed in to change notification settings - Fork 294
Is fs.close() mandatory? #10
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
The operating system will close file descriptors on exit. If you have a long-running process, you should close them yourself though, otherwise you'll eventually run out of file descriptors. |
Thank you. |
Could this be added to the documentation of |
const fs = require("fs");
const file = "/path/to/file/with/contents";
const fd = fs.openSync(file, 'w+');
fs.closeSync(fd);
|
@CEbbinghaus Yes, you should avoid opening the file if you don't want to truncate it. You probably actually want to use the |
For anyone that may stumble upon this thread in future with a similar problem to me I have found the best solution to be: const fs = require("fs");
const file = "/path/to/file/with/contents";
const fd = fs.openSync(file, 'a+');
if (condition) {
fs.truncateSync(fd, 0);
fs.writeSync(fd, content);
}
fs.closeSync(fd); This way if no data is written the file is closed with the same content it had and if we are writing to it we overwrite the data that was there. |
@CEbbinghaus that is unsafe. Use the pattern of writing to a temporary file and renaming. |
Must I close files after
fs.open
andfs.write
in the end of a script?What happens if I don't (in different OSes)?
Does Node closes opened files before normal exit? Before exception exit?
Are there different situations when not closing is safe and when it is not?
The text was updated successfully, but these errors were encountered: