Reading Files in JavaScript

Here’s the translated code and explanation in JavaScript, formatted for Hugo:

Our first program will demonstrate reading files in JavaScript. We’ll cover various methods of reading file contents.

const fs = require('fs').promises;

// Helper function to handle errors
function check(err) {
    if (err) throw err;
}

async function readFiles() {
    try {
        // Read entire file contents into memory
        const dat = await fs.readFile('/tmp/dat', 'utf8');
        console.log(dat);

        // Open file for more controlled reading
        const fileHandle = await fs.open('/tmp/dat', 'r');

        // Read some bytes from the beginning of the file
        const buffer1 = Buffer.alloc(5);
        const { bytesRead: n1 } = await fileHandle.read(buffer1, 0, 5, 0);
        console.log(`${n1} bytes: ${buffer1.toString('utf8', 0, n1)}`);

        // Read from a specific position in the file
        const buffer2 = Buffer.alloc(2);
        const { bytesRead: n2 } = await fileHandle.read(buffer2, 0, 2, 6);
        console.log(`${n2} bytes @ 6: ${buffer2.toString('utf8', 0, n2)}`);

        // Seek to a position relative to the current position
        await fileHandle.read(Buffer.alloc(4), 0, 4, null);

        // Seek to a position relative to the end of the file
        const stats = await fileHandle.stat();
        await fileHandle.read(Buffer.alloc(0), 0, 0, stats.size - 10);

        // Read using a specific number of bytes
        const buffer3 = Buffer.alloc(2);
        const { bytesRead: n3 } = await fileHandle.read(buffer3, 0, 2, 6);
        console.log(`${n3} bytes @ 6: ${buffer3.toString('utf8')}`);

        // Close the file
        await fileHandle.close();

        // Read file using streams for efficiency
        const readStream = fs.createReadStream('/tmp/dat', { highWaterMark: 5 });
        for await (const chunk of readStream) {
            console.log(`5 bytes: ${chunk}`);
            break; // Only read the first chunk
        }

    } catch (err) {
        check(err);
    }
}

readFiles();

To run the program:

$ echo "hello" > /tmp/dat
$ echo "javascript" >> /tmp/dat
$ node reading-files.js
hello
javascript
5 bytes: hello
2 bytes @ 6: ja
2 bytes @ 6: ja
5 bytes: hello

This script demonstrates various methods of reading files in JavaScript:

  1. Reading an entire file into memory using fs.readFile().
  2. Opening a file for more controlled reading with fs.open().
  3. Reading specific bytes from the file using fileHandle.read().
  4. Seeking to different positions in the file.
  5. Using streams for efficient reading of large files.

Note that JavaScript’s file operations are asynchronous by default, so we use async/await to handle promises. The fs.promises API is used to work with promises instead of callbacks.

Error handling is done using try/catch blocks, and the check() function is used to throw errors if they occur.

Next, we’ll look at writing files in JavaScript.