Writing Files in TypeScript
Here’s the TypeScript translation of the Go code example for writing files:
Writing files in TypeScript follows similar patterns to the ones we saw earlier for reading.
Try running the file-writing code:
Then check the contents of the written files:
In this TypeScript version, we use the fs
module to handle file operations. The writeFile
function is used for simple file writing, while createWriteStream
is used for more granular control.
Unlike Go, TypeScript (running on Node.js) uses an asynchronous model for file I/O. We’ve used the synchronous versions of these functions for simplicity, but in a real application, you’d typically use the asynchronous versions to avoid blocking the event loop.
The Buffer
class is used to handle binary data, similar to byte slices in Go.
Instead of defer
, we use a try-finally block to ensure the file is closed even if an error occurs.
The Sync
operation doesn’t have a direct equivalent in Node.js as the OS handles file system syncing, but calling close()
on a file stream ensures all data is written.
Next, we’ll look at applying some of the file I/O ideas we’ve just seen to the stdin
and stdout
streams.