为什么 'fs' 在作为 ES6 模块导入时不起作用?

Why doesn't 'fs' work when imported as an ES6 module?

当我尝试使用对 ES6 模块的新 Node.js 支持(例如 node --experimental-modules script.mjs)时,为什么会出现这样的错误?

// script.mjs
import * as fs from 'fs';

// TypeError: fs.readFile is not a function
fs.readFile('data.csv', 'utf8', (err, data) => {
    if (!err) {
        console.log(data);
    }
});
// TypeError: fs.readdirSync is not a function
fs.readdirSync('.').forEach(fileName => {
    console.log(fileName);
});

您必须使用 import fs from 'fs',而不是 import * as fs from 'fs'

这是因为(至少从mjs文件的角度来看'fs'模块只导出一个东西,叫做default .所以如果你写 import * as fs from 'fs'fs.default.readFile 存在但 fs.readFile 不存在。也许所有 Node.js (CommonJS) 模块都是如此。

令人困惑的是,在 TypeScript 模块中(@types/node 和 ES5 输出),import fs from 'fs' 产生错误

error TS1192: Module '"fs"' has no default export

所以在 TypeScript 中你必须默认写 import * as fs from 'fs';。看来可以使用 tsconfig.json.

中的新 "esModuleInterop": true option 来更改它以匹配 mjs 文件的工作方式

我们可以在我们的代码中像这样简单地导入它

import * as fs from 'fs';

非常适合我,试一试