ยท hands on

Improve your TypeScript workflow with Code Snippets

Learn how to improve your TypeScript workflow by using code snippets. This article provides a code example for logging a JSON response into a file using Node.js and TypeScript.

Sometimes you may want to log a simple JSON response into a file. It's quite easy to do in a Node.js environment with TypeScript. Just require Node's internal fs module and use the writeFileSync function.

Code Example

For CommonJS packages, the following code snippet can be used to write an object into a file:

demo.cts
const payload = { name: 'text' };
require('node:fs').writeFileSync(`dump-${Date.now()}.json`, JSON.stringify(payload));

If your package is an ECMAScript module, you can achieve the same result importing the module dynamically with await import:

demo.mts
const payload = { name: 'text' };
(await import('node:fs')).writeFileSync(`dump-${Date.now()}.json`, JSON.stringify(payload));

Improve Your Workflow

To speed up your development process, convert the provided code into a reusable snippet associated with specific keystrokes. Most modern IDEs offer this functionality to simplify usage. For example, WebStorm has a feature called Live Templates that can automatically convert a sequence of characters into TypeScript code. Similarly, Visual Studio Code offers a feature known simply as Snippets.

As an example, I have assigned the keys "dump" to the code shown above. As a result, I can easily generate log files by typing "dump" and pressing the "Tab" key on my keyboard.

Back to Blog