In Node.js, you can write to files using the fs (File System) module.
-> Below I am sharing some examples which can helping you to do write operation with file
Example:
const fs = require('fs');
const filePath = 'example.txt';
const content = 'Hello, this is some content!';
try {
fs.writeFileSync(filePath, content);
console.log('File written successfully.');
} catch (error) {
console.error('Error writing to file:', error);
}
Example:
const fs = require('fs');
const filePath = 'example.txt';
const content = 'Hello, this is some content!';
fs.writeFile(filePath, content, (error) => {
if (error) {
console.error('Error writing to file:', error);
} else {
console.log('File written successfully.');
}
});
Example:
const fs = require('fs');
const filePath = 'example.txt';
const contentToAppend = '\nThis content is appended.';
fs.appendFile(filePath, contentToAppend, (error) => {
if (error) {
console.error('Error appending to file:', error);
} else {
console.log('Content appended successfully.');
}
});
Work with our skilled Node developers to accelerate your project and boost its performance.
Hire Node.js Developers