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-ghijklIn this TypeScript version:
We use the
fsmodule for file system operations,osfor OS-specific functionality, andpathfor path manipulations.Instead of
os.CreateTemp, we usefs.mkdtempSyncto create a temporary directory and then create a file within it.The
checkfunction is implemented similarly to handle errors.We use
process.on('exit', ...)to set up cleanup operations that will run when the program exits, similar to Go’sdefer.fs.writeFileSyncis used to write data to files, replacing Go’sf.Writeandos.WriteFile.fs.mkdtempSyncis used for both temporary files and directories, with different prefixes.The
os.RemoveAllequivalent in Node.js isfs.rmdirSyncwith therecursive: trueoption.
This TypeScript code provides similar functionality to the original Go code, creating and managing temporary files and directories.