How To Fix The “Cannot Find Module ‘Fs/promises'” In TypeScript

"Cannot find module 'fs/promises'" in TypeScript

In this post, we will share with you the solution for the “Cannot find module ‘fs/promises'” in TypeScript. What does this error mean? Check out the following information.

The reason why we get this problem

The reason why you are getting the error “Cannot find module ‘fs/promises'” in TypeScript is that you have not installed typings for node in your project.

An error will occur if you use ‘fs/promises‘ without setting the node type. See the following example:

import { readFile, writeFile} from "fs/promises";

//…other lines of code

Error:

Solutions for the error “Cannot find module ‘fs/promises'” in TypeScript

The solution to this problem is installing the types for the node before using the ‘fs/promises‘ module. To do that, open the terminal in your root directory and run the command below:

npm i -D @types/node

After successfully running this command, you have typings for the node installed as a dev dependency. 

If the error persists, check your file tsconfig.json. Make sure that the array ‘types’ in object ‘compilerOptions’ contains the value ‘node’. To illustrate, here is an example:

{
  "compilerOptions": {
    "types": [ "node"]
  },
//… other options
}

At this point, it looks like the error has been fixed. Now, TypeScript should be able to find the type definitions for the ‘fs/promises‘ module.

In fact, there is one last way you can try if the error is still not solved. Try deleting your project’s folder ‘node_modules’ and file ‘package-lock.json‘. After that, run the ‘npm install‘ command. You can do all these things by running the following commands:

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

After running the above commands, we recommend you restart the IDE and development server before continuing with your work to avoid the error.

When you have successfully fixed the error, you can already use the command to import the fs module and use it as usual.

Here is a small program that describes how to use it for you:

import * as fs from 'fs';
import * as path from 'path';
function readFileContent() {

  const Contents = fs.readFileSync(
    path.join(__dirname, 'home.ts'),
    {
        encoding: 'utf-8',
        flag:'r'
    },
  );
  console.log(Contents);
}
readFileContent();

Summary

To sum up, that’s all I want to cover in this article. Hopefully, through this article, you have understood how to fix the error “Cannot find module ‘fs/promises'” in TypeScript. Good luck with your projects.

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *