Directories in JavaScript

Here’s the translation of the Go code example to JavaScript, formatted in Markdown suitable for Hugo:

Our first program demonstrates how to work with directories in JavaScript. Here’s the full source code:

const fs = require('fs');
const path = require('path');

function check(err) {
    if (err) {
        throw err;
    }
}

// Create a new sub-directory in the current working directory.
fs.mkdirSync('subdir', { mode: 0o755 });

// When creating temporary directories, it's good practice to clean them up afterwards.
// We'll use a try-finally block to ensure cleanup happens even if an error occurs.
try {
    // Helper function to create a new empty file.
    function createEmptyFile(name) {
        fs.writeFileSync(name, '', { mode: 0o644 });
    }

    createEmptyFile('subdir/file1');

    // We can create a hierarchy of directories, including parents.
    // This is similar to the command-line `mkdir -p`.
    fs.mkdirSync('subdir/parent/child', { recursive: true, mode: 0o755 });

    createEmptyFile('subdir/parent/file2');
    createEmptyFile('subdir/parent/file3');
    createEmptyFile('subdir/parent/child/file4');

    // fs.readdirSync lists directory contents, returning an array of file names.
    let files = fs.readdirSync('subdir/parent');

    console.log('Listing subdir/parent');
    for (let file of files) {
        let stats = fs.statSync(path.join('subdir/parent', file));
        console.log(' ', file, stats.isDirectory());
    }

    // process.chdir lets us change the current working directory, similarly to `cd`.
    process.chdir('subdir/parent/child');

    // Now we'll see the contents of `subdir/parent/child` when listing the current directory.
    files = fs.readdirSync('.');

    console.log('Listing subdir/parent/child');
    for (let file of files) {
        let stats = fs.statSync(file);
        console.log(' ', file, stats.isDirectory());
    }

    // Change back to where we started.
    process.chdir('../../..');

    // We can also visit a directory recursively, including all its sub-directories.
    console.log('Visiting subdir');
    visitDir('subdir');

} finally {
    // Clean up: remove the directory and all its contents
    fs.rmdirSync('subdir', { recursive: true });
}

// visitDir is called for every file or directory found recursively
function visitDir(dir) {
    let files = fs.readdirSync(dir);
    for (let file of files) {
        let fullPath = path.join(dir, file);
        let stats = fs.statSync(fullPath);
        console.log(' ', fullPath, stats.isDirectory());
        if (stats.isDirectory()) {
            visitDir(fullPath);
        }
    }
}

This script demonstrates various operations with directories in JavaScript:

  1. Creating directories and files
  2. Listing directory contents
  3. Changing the current working directory
  4. Recursively visiting a directory structure

To run the program, save it as directories.js and use node:

$ node directories.js
Listing subdir/parent
  child true
  file2 false
  file3 false
Listing subdir/parent/child
  file4 false
Visiting subdir
  subdir/file1 false
  subdir/parent true
  subdir/parent/child true
  subdir/parent/child/file4 false
  subdir/parent/file2 false
  subdir/parent/file3 false

This example showcases how to perform common directory operations in JavaScript using the built-in fs (File System) and path modules. It’s important to note that these operations are synchronous for simplicity, but in real-world applications, you might want to use the asynchronous versions of these functions for better performance, especially when dealing with large directory structures or in a server environment.