DeveloperBreeze

Snippets Programming Tutorials, Guides & Best Practices

Explore 196+ expertly crafted snippets tutorials, components, and code examples. Stay productive and build faster with proven implementation strategies and design patterns from DeveloperBreeze.

Read and Write Files in Node.js using 'fs' module

Code January 26, 2024
javascript

// Import 'fs' module
const fs = require('fs');

// Read a file
fs.readFile('file.txt', 'utf8', (err, data) => {
  if (err) throw err;
  console.log(data);
});

// Write to a file
fs.writeFile('newfile.txt', 'Hello, Node.js!', (err) => {
  if (err) throw err;
  console.log('File written successfully.');
});