Search code examples
javascriptnode.jstypescriptnode.js-fs

fs/promises API in TypeScript is not compiling correctly in JavaScript


I was recently working with TypeScript and the fs/promises API and got this error when the TypeScript code was compiled and run. I got this error saying:

internal/modules/cjs/loader.js:968
  throw err;
  ^

Error: Cannot find module 'fs/promises'

When I looked at the compiled code, this is what I found...

var promises_1 = require("fs/promises");

Which started working by changing it to

var promises_1 = require("fs").promises;

This is my TypeScript file import:

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

My package.json file:

 "devDependencies": {
    "@types/cheerio": "^0.22.22",
    "@types/got": "^9.6.11",
    "@types/node": "^14.14.6"
  },
  "dependencies": {
    "cheerio": "^1.0.0-rc.3",
    "got": "^11.8.0"
  }

And my tsconfig.json file:

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "strict": true,
    "outDir": "dist",
    "sourceMap": true
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules", "**/*.spec.ts"]
}

Node.js version: 12.18.0

How can I fix this?


Solution

  • The error was due to unsupported Node version 12.x which doesn't support this require statement...

    var promises_1 = require("fs/promises");
    

    but this works

    var promises_1 = require("fs").promises;
    

    This can be solved by updating the Node to the latest.