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:
We use the
fs
module for file system operations,os
for OS-specific functionality, andpath
for path manipulations.Instead of
os.CreateTemp
, we usefs.mkdtempSync
to create a temporary directory and then create a file within it.The
check
function 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.writeFileSync
is used to write data to files, replacing Go’sf.Write
andos.WriteFile
.fs.mkdtempSync
is used for both temporary files and directories, with different prefixes.The
os.RemoveAll
equivalent in Node.js isfs.rmdirSync
with therecursive: true
option.
This TypeScript code provides similar functionality to the original Go code, creating and managing temporary files and directories.