Understanding Node.js, the fs File System Module, and the path Module

Initial Exposure to Node.js

JavaScript execution in browsers relies on engine-specific interpreters:

  • Chrome uses V8
  • Firefox uses OdinMonkey
  • Safari uses JavaScriptCore
  • Internet Explorer uses Chakra

Among these, V8 offers top-tier performance. Browsers also expose DOM and BOM APIs, enabling JavaScript to interact with web pages.

The JavaScript runtime environment includes both the engine (e.g., V8) and built-in APIs specific to that environment. While browsers provide frontend capabilities, Node.js serves as a backend runtime powered by V8, without access to browser-specific APIs like DOM or BOM.

Node.js enables JavaScript to handle server-side tasks such as:

  • Building web apps with Express
  • Creating desktop apps via Electron
  • Developing REST APIs using Restify
  • Interfacing with databases and building CLI tools

Learning Node.js follows this path: core JavaScript → built-in modules (fs, path, http) → third-party packages (Express, MySQL, etc.).

Useful terminal tips:

  • Shift + Right-click → "Open PowerShell here"
  • ↑ recalls previous commands
  • Tab auto-completes paths
  • ESC clears the current line
  • cls clears the terminal
  • ./ denotes the current directory (often optional)

The fs File System Module

The fs module provides file I/O operations. Import it with:

const fs = require('fs');

Reading Files

fs.readFile(path, [encoding], callback) reads a file asynchronously:

fs.readFile('./files/sample.txt', 'utf8', (err, content) => {
  if (err) {
    console.error('Read failed:', err.message);
    return;
  }
  console.log('File content:', content);
});

Writing Files

fs.writeFile(path, data, [encoding], callback) writes data to a file (overwriting existing content):

fs.writeFile('./files/output.txt', 'Hello, Node!', err => {
  if (err) {
    console.error('Write failed:', err.message);
    return;
  }
  console.log('File written successfully');
});

⚠️ fs.writeFile() creates files but not directories. It also overwrites existing files.

Handling Path Resolution

Using relative paths like ./file.txt can cause issues becuase Node resolves them relative to the current working directory (where node was run), not the script’s location.

Solution: Use __dirname, which always refers to the directory of the current script:

fs.readFile(__dirname + '/files/sample.txt', 'utf8', callback);

However, string concatenation for paths is error-prone across operating systems.


The path Module

The path module handles cross-platform path operations:

const path = require('path');

Path Joining

Use path.join() to safely combine path segments:

const fullPath = path.join(__dirname, 'files', 'sample.txt');
fs.readFile(fullPath, 'utf8', callback);

This automatically handles slashes and resolves .. and . segments:

console.log(path.join('/a', '/b/c', '../../', './d', 'e')); // /a/b/d/e

Extracting Filename and Extension

  • path.basename(path, [ext]) returns the filename:

    const file = '/docs/report.pdf';
    console.log(path.basename(file));        // 'report.pdf'
    console.log(path.basename(file, '.pdf')); // 'report'
    
  • path.extname(path) returns the file extansion:

    console.log(path.extname('/images/photo.png')); // '.png'
    

Alwayss prefer path.join() over manual string concatenation for robust, cross-platform path handling.

Tags: Node.js fs Path File System javascript

Posted on Fri, 16 Oct 2026 16:34:18 +0000 by ariliquin