Write Files
(This is part of a brief series on the fs module)
Writing Files Syncrhonously
The writeFileSync
method of the fs
module can be used to write files to disk:
const { writeFileSync } = require('fs');
const FILE_TO_WRITE = './../from-writeFileSync.txt';
writeFileSync(FILE_TO_WRITE,'this is a string\n');
Leveraging Flags For More Explicit FInteraction Expectations
Node has a bunch of file system flags that can be used to be more explicit about interaction expectations. Here's a few examples:
ax: Fail When The File Already Exists
// assuming the file already exists
const { writeFileSync } = require('fs');
const FILE_TO_WRITE = './../from-writeFileSync.txt';
writeFileSync(FILE_TO_WRITE, 'this is a string\n', { flag: 'ax' });
// will throw an error:
// Error: EEXIST: file already exists, open './../from-writeFileSync.txt'
a+ Append When The File Already Exists
const { writeFileSync } = require('fs');
const FILE_TO_WRITE = './../from-writeFileSync.txt';
writeFileSync(FILE_TO_WRITE, 'this is a string\n', { flag: 'a+' });
Keeping The Event Loop Open with writeFile
const { writeFile } = require('fs');
const FILE_TO_WRITE = './../from-writeFile.txt';
function writeFileCallback(err) {
if (err) {
console.error(err);
return;
}
console.log('done writing');
}
writeFile(FILE_TO_WRITE, 'this is a string\n', writeFileCallback);
Keeping The Event Loop Open with The Promise API
the node fs module has a nice built-in promise-syntax api:
const { writeFile } = require('fs/promises');
const FILE_TO_WRITE = './../new-file.txt';
writeFile(FILE_TO_WRITE, 'this is a string\n').then(() => {
console.log('done writing!')
}).catch(console.log);