Loading

Quipoin Menu

Learn • Practice • Grow

node-js / File System Advanced
tutorial

File System Advanced

Now that you know the basics of reading and writing files, it's time to explore the more powerful features of the File System module. Think of this as moving from a basic notepad to a full-featured file manager!

Working with Directories

Just like files, you can create, read, and delete directories.

Creating Directories
<!-- Create a single directory -->
fs.mkdir('mydir', (err) => {
  if (err) throw err;
  console.log('Directory created');
});

<!-- Create nested directories with recursive option -->
fs.mkdir('parent/child/grandchild', { recursive: true }, (err) => {
  if (err) throw err;
  console.log('Nested directories created');
});

Reading Directories
fs.readdir('.', (err, files) => {
  if (err) throw err;
  console.log('Files in current directory:');
  files.forEach(file => {
    console.log(' -', file);
  });
});

Removing Directories
<!-- Remove empty directory -->
fs.rmdir('mydir', (err) => {
  if (err) throw err;
  console.log('Directory removed');
});

<!-- Remove directory with contents (recursive) – Node.js v14+ -->
fs.rm('parent', { recursive: true, force: true }, (err) => {
  if (err) throw err;
  console.log('Directory and all contents removed');
});

File Information (Stats)

Get detailed information about a file or directory.
fs.stat('sample.txt', (err, stats) => {
  if (err) throw err;
 
  console.log('File size:', stats.size, 'bytes');
  console.log('Is file?', stats.isFile());
  console.log('Is directory?', stats.isDirectory());
  console.log('Created:', stats.birthtime);
  console.log('Modified:', stats.mtime);
  console.log('Permissions:', stats.mode.toString(8));
});

Watching Files for Changes

Node.js can watch files and notify you when they change – great for auto-reload tools, build systems, etc.
<!-- Watch a file for changes -->
fs.watch('sample.txt', (eventType, filename) => {
  console.log(`File ${filename} changed: ${eventType}`);
});

<!-- Watch a directory for changes -->
fs.watch('.', { recursive: true }, (eventType, filename) => {
  console.log(`${filename} - ${eventType}`);
});

Renaming Files and Directories
fs.rename('oldname.txt', 'newname.txt', (err) => {
  if (err) throw err;
  console.log('File renamed');
});

Copying Files

Node.js v8.5+ has built-in copy functions.
<!-- Copy file -->
fs.copyFile('source.txt', 'destination.txt', (err) => {
  if (err) throw err;
  console.log('File copied');
});

Working with File Streams

For large files, reading/writing the entire file at once can use too much memory. Streams process data in chunks.
<!-- Create a readable stream -->
const readStream = fs.createReadStream('large-file.txt', 'utf8');

readStream.on('data', (chunk) => {
  console.log('Received chunk:', chunk.length, 'bytes');
});

readStream.on('end', () => {
  console.log('Finished reading file');
});

readStream.on('error', (err) => {
  console.error('Error:', err);
});

<!-- Piping streams – copy file efficiently -->
const readStream = fs.createReadStream('source.txt');
const writeStream = fs.createWriteStream('destination.txt');

readStream.pipe(writeStream);

readStream.on('end', () => {
  console.log('Copy complete');
});

Using fs.promises (Modern Async/Await)

Node.js provides a promise-based version of the fs module – much cleaner with async/await.
const fs = require('fs').promises;

async function fileOperations() {
  try {
    <!-- Read file -->
    const data = await fs.readFile('sample.txt', 'utf8');
    console.log('Content:', data);
   
    <!-- Write file -->
    await fs.writeFile('new.txt', 'Hello from promises!');
   
    <!-- Get file stats -->
    const stats = await fs.stat('new.txt');
    console.log('File size:', stats.size);
   
    <!-- Read directory -->
    const files = await fs.readdir('.');
    console.log('Files:', files);
  } catch (err) {
    console.error('Error:', err);
  }
}

fileOperations();

Two Minute Drill

  • Create directories with `fs.mkdir()` and `recursive: true` for nested paths.
  • Read directory contents with `fs.readdir()`.
  • Get file details with `fs.stat()` – size, type, timestamps, permissions.
  • Watch files/directories for changes with `fs.watch()`.
  • For large files, use streams to process data in chunks.
  • Modern code should use `fs.promises` with async/await.

Need more clarification?

Drop us an email at career@quipoinfotech.com