Temporary Files And Directories in TypeScript

Throughout program execution, we often want to create data that isn’t needed after the program exits. Temporary files and directories are useful for this purpose since they don’t pollute the file system over time.

import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';

function check(e: Error | null): void {
    if (e !== null) {
        throw e;
    }
}

function main() {
    // The easiest way to create a temporary file is by
    // using the `fs.mkdtempSync` function to create a temporary
    // directory, and then creating a file within it.
    const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'sample-'));
    const tempFile = path.join(tempDir, 'tempfile');
    fs.writeFileSync(tempFile, '');

    // Display the name of the temporary file. On
    // Unix-based OSes the directory will likely be `/tmp`.
    console.log("Temp file name:", tempFile);

    // Clean up the file after we're done. Node.js doesn't
    // automatically clean up temporary files, so it's good
    // practice to do this explicitly.
    process.on('exit', () => {
        fs.unlinkSync(tempFile);
        fs.rmdirSync(tempDir);
    });

    // We can write some data to the file.
    fs.writeFileSync(tempFile, Buffer.from([1, 2, 3, 4]));

    // If we intend to create many temporary files, we may
    // prefer to create a temporary *directory*.
    const tempDirName = fs.mkdtempSync(path.join(os.tmpdir(), 'sampledir-'));
    console.log("Temp dir name:", tempDirName);

    // Clean up the directory after we're done.
    process.on('exit', () => {
        fs.rmdirSync(tempDirName, { recursive: true });
    });

    // Now we can synthesize temporary file names by
    // prefixing them with our temporary directory.
    const fname = path.join(tempDirName, 'file1');
    fs.writeFileSync(fname, Buffer.from([1, 2]));
}

main();

To run the program:

$ ts-node temporary-files-and-directories.ts
Temp file name: /tmp/sample-abcdef/tempfile
Temp dir name: /tmp/sampledir-ghijkl

In this TypeScript version:

  1. We use the fs module for file system operations, os for OS-specific functionality, and path for path manipulations.

  2. Instead of os.CreateTemp, we use fs.mkdtempSync to create a temporary directory and then create a file within it.

  3. The check function is implemented similarly to handle errors.

  4. We use process.on('exit', ...) to set up cleanup operations that will run when the program exits, similar to Go’s defer.

  5. fs.writeFileSync is used to write data to files, replacing Go’s f.Write and os.WriteFile.

  6. fs.mkdtempSync is used for both temporary files and directories, with different prefixes.

  7. The os.RemoveAll equivalent in Node.js is fs.rmdirSync with the recursive: true option.

This TypeScript code provides similar functionality to the original Go code, creating and managing temporary files and directories.