Rez Moss

Rez Moss

Personal Musings: A Blog for the Tech-Savvy and Curious Mind

Working with Files in Node.js

Aug 2017

Node.js provides a built-in fs (File System) module that allows you to work with files easily. Here’s a quick guide to common file operations:

Reading a File

To read the contents of a file:

const fs = require('fs');

fs.readFile('example.txt', 'utf8', (err, data) => {
  if (err) {
    console.error('Error reading file:', err);
    return;
  }
  console.log(data);
});

Writing to a File

To write content to a file:

const fs = require('fs');

const content = 'Hello, Node.js!';

fs.writeFile('output.txt', content, (err) => {
  if (err) {
    console.error('Error writing file:', err);
    return;
  }
  console.log('File written successfully');
});

Appending to a File

To add content to the end of a file:

const fs = require('fs');

fs.appendFile('log.txt', 'New log entry\n', (err) => {
  if (err) {
    console.error('Error appending to file:', err);
    return;
  }
  console.log('Data appended to file');
});

Checking if a File Exists

To check if a file exists:

const fs = require('fs');

fs.access('myfile.txt', fs.constants.F_OK, (err) => {
  console.log(err ? 'File does not exist' : 'File exists');
});

Deleting a File

To delete a file:

const fs = require('fs');

fs.unlink('unnecessary.txt', (err) => {
  if (err) {
    console.error('Error deleting file:', err);
    return;
  }
  console.log('File deleted successfully');
});

Remember, these operations are asynchronous by default. For synchronous versions, use methods like readFileSync, writeFileSync, etc., but be cautious as they can block the event loop.