130

I'm running on a MacBook Air. I installed VS Code as an IDE and also have TypeScript installed.

I have a simple file with just this line:

import fs = require('fs');

I'm getting a red squiggly under the 'fs' inside the parenthesis and the error message is [ts] Cannot find module 'fs'. The file has a .ts extension. I'm new to JavaScript and to TypeScript, but I was under the impression that fs was a core module, so how could it not be found? How do I fix the problem?

Other things that I tried already:

  • Putting a simple function body in the file and then compiling on the command line with tsc. I get an essentially equivalent error there: error TS2307: Cannot find module 'fs'.
  • On the command line sudo npm install fs -g. This reports apparent success, but doesn't fix the problem.

I poked around SE and the web, but the answers that seemed close all appear to assume that 'fs' is available.

shreyasm-dev
  • 2,711
  • 5
  • 16
  • 34
Brick
  • 3,998
  • 8
  • 27
  • 47

12 Answers12

166

You need to include the definition file for node.

TypeScript 2.0+

Install using npm:

npm install --save-dev @types/node

TypeScript < 2.0

If you use typings then you can run this command:

typings install dt~node --global --save

Or if you are using typings < 1.0 run:

typings install node --ambient --save

Or if all else fails, manually download the file here and include it in your project.

David Sherret
  • 101,669
  • 28
  • 188
  • 178
  • 1
    I used the command that you had prior to your edit, and that did the trick. (`typings install node --ambient --save`) Thanks! – Brick May 16 '16 at 18:54
  • @Brick yes that will work. The command in the answer is for typings 1.0 which was just released – David Sherret May 16 '16 at 18:55
  • This is out of date, these days types should usually be installed with npm, as in [Abe's answer below](https://stackoverflow.com/a/41413226/874671). – dshepherd Feb 02 '18 at 10:08
  • 1
    With yarn: `yarn add @types/node --dev` – Jonathan H Feb 20 '18 at 09:08
  • After installing `@types/node`, you may need to restart Code to get it to recognize the modules properly. This should only be the case with native node modules, and may not even be an issue for you depending on your build of Code. – Don Jun 12 '18 at 01:14
  • 2
    Tried it. But still didn't work for me. Any other reason for still getting `Error: Can't resolve 'fs'` ? – barath Jul 15 '19 at 06:15
  • 2
    @barath did you find a solution? I also have this error. – Vidy Videni Jan 26 '22 at 01:52
  • For someone who already has @types/node installed but still gets this error, you need to add "node" into the "types" field of tsconfig.json. Check https://stackoverflow.com/a/41413226/10706866 to get the gist of the syntax – khoi nguyen Mar 20 '23 at 03:18
63

There is a better way now without going to the previous tsd or typings tools. NPM now has the @types package for typescript. In this example you need the package @types/node:

npm install "@types/node" --save-dev

Make sure you are using the save-dev option to only install the types in development mode, not in production. You should have the latest node libraries when use the npm install "@types/" syntax...

It not finding the fs package because the previous tools typings most likely not using the latest node.d.ts definition file.

Your tsconfig.json file needs to be updated to find these type packages. My example if using jquery, jqueryui and node types. Assuming you need the syntax to work for your code editor as well, in this case the 'atom' code editor

{
"compileOnSave": false,
"compilerOptions": {
    "rootDir": "src",
    "sourceMap": true,
    "target": "es5",
    "module": "amd",
    "declaration": false,
    "noImplicitAny": false,
    "removeComments": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "moduleResolution": "node",
    "lib": ["es2015", "dom"],
    "baseUrl": "./",
    "typeRoots": [
        "node_modules/@types"
    ],
    "types": [
        "jquery",
        "jqueryui",
        "node"
    ],
    "paths": {
        "src/*": ["src/*"]
    }
},
"exclude": [
    "node_modules",
    "dist",
    "build"
],
"filesGlob": [
    "./src/**/*.ts",
    "./test/**/*.ts",
    "./typings/index.d.ts",
    "./custom_typings/**/*.d.ts",
    "./node_modules/@types/**/*.d.ts"
],
"atom": {
    "rewriteTsconfig": false
}
}
dshepherd
  • 4,989
  • 4
  • 39
  • 46
Abe
  • 651
  • 1
  • 5
  • 4
43

"fs" is a core Node module and I think your import statement syntax is a little off. Try:

import * as fs from "fs";
Eric N
  • 2,136
  • 13
  • 13
  • Ah the typings for Node isn't included. Try adding this file and a reference path to it: https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/node/node.d.ts – Eric N May 16 '16 at 18:51
  • 2
    @EricN The page leads to a 404. Typings are needed even if the module is part of the whole NodeJs core ? – Jacks Jan 10 '17 at 15:40
  • Yeah the typing is necessary. Node isn't written in Typescript so it doesn't have any of the type data that Typescript looks for. The definition file provides all that type data for you. – Eric N Jan 10 '17 at 21:08
28

All you need is "moduleResolution" set to "node" in your tsconfig.json:

{
  "compilerOptions": {
      ...
      "moduleResolution": "node"
      ...
  }
}

execute

npm install @types/node --save-dev

and now you can use standard TypeScript import:

import * as fs from "fs";
Brick
  • 3,998
  • 8
  • 27
  • 47
yrtimiD
  • 535
  • 7
  • 7
16

You have three options in tsconfig.json (here: Node 11+), see docs:

Either specifiy both typeRoots and types, only typeRoots or remove both lines completely (recommended):

{"compilerOptions": {
  ...
  "typeRoots": ["node_modules/@types"],  // "typeRoots": [] -> won't work
  "types": ["node"]                      // "types": [] -> won't work
}}

Install types:

npm install --save-dev @types/node

Use promise based file system (e.g to use async / await):

import {promises as fs} from 'fs';

async function foo() {
    ...
    await fs.writeFile('./yourPath', 'YourContent');
}
User Rebo
  • 3,056
  • 25
  • 30
  • When I created a declarations folder to put my `.d.ts` files in and created a `typeRoots` array in my `compilerOptions` I had not specified the `node_modules/@types` and that's what caused the error for me. Once I added that to the `typeRoots` array, it worked again. – str8up7od Sep 07 '20 at 00:28
  • Excellent answer. Unlike 90% of folks here, I already had `node` types installed but was running into the issue where core `node` modules (like `os` where not being found at *runtime*) – Robert Oct 25 '21 at 11:48
  • Thanks. I was missing `types:["node"]` in my tsconfig:compilerOptions. – John Hatton Dec 26 '22 at 16:14
2

Typescript knows about modules based upon conventions , check Module resolution for more detail.

Also for IDE to know about fs module, you have to provide typings for node.

Also check this github issue

Madhu Ranjan
  • 17,334
  • 7
  • 60
  • 69
0

on my side this work

 const fs = require('fs') as typeof import('fs');

of for nwjs with vitejs

 const fs = nw.require('fs') as typeof import('fs');

this remove the any

jon
  • 1,494
  • 3
  • 16
  • 29
0

You can also get this kind of error if your file (script) is inside a directory that starts with . : https://github.com/microsoft/TypeScript/issues/13399

I had the same exact problem (Cannot find module 'fs' or its corresponding type declarations.) although @types/node was installed. My script was in .husky directory and adding:

    "include": [
        "./**/*",
        "./.husky/**/*",
    ],

to the tsconfig.json solved the problem.

cimak
  • 1,765
  • 3
  • 15
  • 18
0

Check your tsconfig.json to see if you have a bad include setting.

I ran into this issue because my tsconfig.json file specified an include list that did not include the file I had the error in. In other words, the file wasn't being properly processed by TypeScript.

In my case, my include was set to ["src"], but my file was inside a subdirectory called scripts. After adjusting include to ["scripts", "src"], the error was fixed.

aardvarkk
  • 14,955
  • 7
  • 67
  • 96
0

In addition to checking the contents of tsconfig.json for the "types": ["node"] setting, you might also want to take a look for the same content in tsconfig.app.json (if you have one).

wmm2
  • 11
  • 2
  • 2
    Hey @wmm2! Glad you could join the community! When putting code in your answer, you can make it a lot more readable as such by selecting the text, and pressing `Ctrl` + `K`. – Robert Bradley May 12 '23 at 19:31
0

I resolved this issue by updating npm version and npm install "@types/node" --save-dev

Sagarika
  • 31
  • 7
0

If you have installed the @types/node package and still having the TS error, try the following:

  1. add "node" to "compileOptions" "types" in tsconfig.json

e.g.

"compileOptions": {
    "types": ["node"]
}
  1. also, add "node" to "compilerOptions" "types" in tsconfig.app.json

  2. save all and restart TS server, by doing the following:

  • Mac: Cmd + Shift + P
  • Win: Ctrl + Shift + P

enter image description here

Gass
  • 7,536
  • 3
  • 37
  • 41