ยท 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. 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.

Templates in WebStorm

For example, WebStorm has a feature called Live Templates that can automatically convert a sequence of characters into TypeScript code.

Templates in Visual Studio Code

Visual Studio Code offers a feature known simply as Snippets. You can define your own code snippets by using "Show All Commands" and selecting "Snippets: Configure User Snippets". This will allow you to create snippets for TypeScript files which will be stored in the following path on Windows:

%APPDATA%/Code/User/Snippets/typescript.json

Within this file, you can now set up your own snippets such as "dump":

{
  "Dump Logs": {
    "body": ["(await import('node:fs')).writeFileSync(`dump-${Date.now()}.json`, JSON.stringify(${1:payload}));$0"],
    "description": "Dump Logs",
    "prefix": "dump"
  }
}

To use the snippet, open a TypeScript file, then use "Show All Commands" and select "Snippets: Insert Snippet" to finally select "dump".

Back to Blog