write-file-atomic
's direct dependencies. Data on all dependencies, including transitive ones, is available via CSV download.Name | Version | Size | License | Type | Vulnerabilities |
---|---|---|---|---|---|
graceful-fs | 4.2.11 | 9.57 kB | ISC | prod | |
imurmurhash | 0.1.4 | 4.21 kB | MIT | prod | |
slide | 1.1.6 | 4.29 kB | ISC | prod |
The npm package "write-file-atomic" works as an extension to Node.js' fs.writeFile
and introduces the ability to write data to a file atomically, with configurable file ownership. The way it functions is by writing data to a temporary file and then renaming it to the desired file name once the operation is complete. This ensures the operation is atomic and improves data integrity by guaranteeing that the file will not be in a corrupted or incomplete state even if an error or process interruption occurs during writing. It also allows for setting user and group ownership (UID/GID) of the file.
To use write-file-atomic, start by installing it using npm. Once installed, it can be required at the top of your JavaScript file using the following syntax: var writeFileAtomic = require('write-file-atomic')
. Now, to write data to a file atomically, use the following syntax:
writeFileAtomic('filename.txt', 'Data to write', {chown:{uid:100,gid:50}}, function (err) {
if (err) throw err;
console.log('File has been saved!');
});
Alternatively, this package also supports the async/await syntax. The equivalent async/await code would be:
(async () => {
try {
await writeFileAtomic('filename.txt', 'Data to write', {chown:{uid:100,gid:50}});
console.log('File has been saved!');
} catch (err) {
console.error(err);
process.exit(1);
}
})();
It also exposes a synchronous version of the writeFileAtomic function which can be used as follows:
var writeFileAtomicSync = require('write-file-atomic').sync;
writeFileAtomicSync('filename.txt', 'Data to write', {chown:{uid:100,gid:50}});