Writing Files in JavaScript

Here’s the translation of the Go code to JavaScript, along with explanations in Markdown format suitable for Hugo:

Writing files in JavaScript follows similar patterns to the ones we saw earlier for reading.

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

async function writeFiles() {
    // To start, here's how to dump a string (or just bytes) into a file.
    try {
        await fs.writeFile('/tmp/dat1', 'hello\njavascript\n');
        console.log('File written successfully');
    } catch (err) {
        console.error('Error writing file:', err);
    }

    // For more granular writes, open a file for writing.
    try {
        const file = await fs.open('/tmp/dat2', 'w');

        // You can write strings as you'd expect.
        await file.writeFile('some\n');
        console.log('Wrote 5 bytes');

        // WriteString is not available in Node.js, but we can use write
        await file.write('writes\n');
        console.log('Wrote 7 bytes');

        // bufio provides buffered writers in addition to the buffered readers we saw earlier.
        // In Node.js, we can use a writable stream for buffered writing
        const writer = fs.createWriteStream('/tmp/dat2', { flags: 'a' });
        writer.write('buffered\n');
        console.log('Wrote 9 bytes');

        // Use end to ensure all buffered operations have been applied to the underlying writer.
        writer.end();

        // Close the file
        await file.close();
    } catch (err) {
        console.error('Error:', err);
    }
}

writeFiles();

Try running the file-writing code.

$ node writing-files.js
File written successfully
Wrote 5 bytes
Wrote 7 bytes
Wrote 9 bytes

Then check the contents of the written files.

$ cat /tmp/dat1
hello
javascript

$ cat /tmp/dat2
some
writes
buffered

Next we’ll look at applying some of the file I/O ideas we’ve just seen to the stdin and stdout streams.