Borislav Hadzhiev
Sun Feb 20 2022·2 min read
Photo by Jamie Street
To import and use the fs
module in TypeScript, make sure to install the type
definitions for node
by running npm i -D @types/node
and import fs
with
the following line import * as fs from 'fs'
, or
import { promises as fsPromises } from 'fs'
if using fs promises.
node
by opening your terminal in your project's root directory and running the following command.npm i -D @types/node
This will add the typings for node as a development dependency in your project.
The node typings include the type definitions for the built-in fs
module.
Here is an example of how to import and use fs
. I'll post a code snippet that
uses the module synchronously and the next code snippet will use the async
version of the same methods.
import * as fs from 'fs'; import * as path from 'path'; function readFile() { const dirContents = fs.readdirSync(__dirname); console.log(dirContents); const fileContents = fs.readFileSync( path.join(__dirname, 'another-file.ts'), { encoding: 'utf-8', }, ); console.log(fileContents); } readFile();
We imported the fs
and path
built-in modules and used the
readdirSync
and
readFileSync
methods.
The readdirSync
method reads the contents of a directory and readFileSync
-
the contents of a specific file.
another-file.ts
located in the same directory where your fs-related code is.Here is the output after running the code from the snippet.
Now let's look at how you would use the promises version of the fs
module.
Here is a code snippet that uses the async (promises) version of the same methods.
import { promises as fsPromises } from 'fs'; import * as path from 'path'; async function readFile() { try { // ✅ Read contents of directory const dirContents = await fsPromises.readdir(__dirname); console.log(dirContents); // ✅ Read contents of `another-file.ts` in the same directory const fileContents = await fsPromises.readFile( path.join(__dirname, './another-file.ts'), { encoding: 'utf-8' }, ); console.log(fileContents); } catch (err) { console.log('error is: ', err); } } readFile();
Notice that the import statement is different, now we are importing promises
from fs
.
We used the fsPromises.readdir method to read the contents of the directory and the fsPromises.readFile method to read the contents of a file.
The example assumes that you have a file named another-file.ts
that is located
in the same directory.
If you need to read more about a specific method the fs
module implements and
how to use it, check out the
Node.js docs for fs.