Borislav Hadzhiev
Sun Feb 20 2022·2 min read
Photo by Sasha Panarin
To solve the "Cannot find module fs
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 * as fs from 'fs'
.
Make sure to install the typings for node, by opening your terminal in your project's root directory and running the following command:
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.
import * as fs from 'fs'; console.log(fs);
If your error has not been resolved, open your tsconfig.json
file and make
sure the types
array contains the string node
.
{ "compilerOptions": { "types": [ "node" ] }, }
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.
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 a file in the same directory named
another-file.ts
with the fs
module using TypeScript.
import * as fs from 'fs'; import * as path from 'path'; console.log( fs.readFileSync(path.join(__dirname, './another-file.ts'), { encoding: 'utf-8', }), );
And here is the output in my terminal showing the contents of another-file.ts
.