Fix - Cannot find module 'fs/promises' Error in TypeScript

avatar

Borislav Hadzhiev

Sun Feb 20 20222 min read

banner

Photo by Jamie Street

Fix - Cannot find module 'fs/promises' Error in TypeScript #

To solve the "Cannot find module fs/promises or its corresponding type declarations" error, install the types for node by running the command npm i -D @types/node. You can then import fs with the following line of code import { promises as fsPromises } from 'fs'.

cannot find module fs promises

Make sure to install the typings for node, by opening your terminal in your project's root directory and running the following command:

shell
npm i -D @types/node

This will install the typings for node as a dev dependency in your project.

Now you are able to import the fs module with the following line of code.

index.ts
import { promises as fsPromises } from 'fs';

If your error has not been resolved, open your tsconfig.json file and make sure the types array contains the string node.

tsconfig.json
{ "compilerOptions": { "types": [ "node" ] }, }
This should fix the error and now TypeScript should be able to find the type definitions for the fs module.

If the error is not resolved, try to delete your node_modules and package-lock.json files, re-run npm install and restart your IDE.

shell
rm -rf node_modules package-lock.json npm install

Make sure to restart your IDE if the error still persists. VSCode glitches often and a reboot solves things sometimes.

Here is an example of how you would read the contents of a directory and the contents of a file named another-file.ts located in the same directory using fs promises.

index.ts
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();

You could rename the import to something else if fsPromises seems too long, e.g. fsp, etc.

Here is the output in my terminal, showing the files in the directory and the contents of another-file.ts.

fs promises read file success

Use the search field on my Home Page to filter through my more than 1,000 articles.