node.js - 如何修复找不到模块 'fs'

标签 node.js angular typescript fs

当我尝试使用 writeFile Angular 从 fs 导入它时,然后我尝试运行 ngserve 并在 src/app/app.component.ts(2,27) 中得到 ERROR: error TS2307: Cannot find module 'fs'.

我猜我在某个地方缺少一个简单的选项,比如当你想使用ng-model时,你需要在app.modules.ts中导入formsModule

我正在使用:

vscode: 1.34

Angular CLI: 8.0.1
Node: 10.15.3
OS: win32 x64
Angular: 8.0.0
... animations, common, compiler, compiler-cli, core, forms
... language-service, platform-browser, platform-browser-dynamic
... router

Package                           Version
-----------------------------------------------------------
@angular-devkit/architect         0.800.1
@angular-devkit/build-angular     0.800.1
@angular-devkit/build-optimizer   0.800.1
@angular-devkit/build-webpack     0.800.1
@angular-devkit/core              8.0.1
@angular-devkit/schematics        8.0.1
@angular/cli                      8.0.1
@ngtools/webpack                  8.0.1
@schematics/angular               8.0.1
@schematics/update                0.800.1
rxjs                              6.4.0
typescript                        3.4.5
webpack                           4.30.0

我的 tsconfig 如下所示:

{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "module": "esnext",
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "importHelpers": true,
    "target": "es2015",
    "typeRoots": ["node_modules/@types"],
    "lib": ["es2018", "dom"],
    "types": ["node"]
  }
}

最佳答案

您指的是NodeJS模块fs ?如果是这样,那么该模块仅在 NodeJS 运行时可用。

我假设您正在编译 Angular 网络应用程序。如果是这种情况,请记住浏览器没有 fs也没有任何其他 Node 模块;就像 Node 没有 fetch 一样或window对象或 API。

作为应用程序捆绑过程的一部分,Angular 编译器无法解析 fs到引用的包或已知的 Web API,从而导致您看到的消息。

如果您需要客户端类似文件的功能,请考虑使用类似的 Web API,例如 localStorage .

https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

如果您需要对磁盘和文件系统进行低级访问,那么您需要一些“后端”运行时/SDK/语言,例如 NodeJS、Python 等。

可以在客户端Javascript中处理文件。您只需要在浏览器允许的范围内工作即可。例如,您可以使用 <input type="file"> 来访问文件的内容。标记,然后处理 FileList对象。

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/file

同样,您可以启动客户端“下载”以让用户保存文件。

https://npmjs.com/package/file-saver

关于node.js - 如何修复找不到模块 'fs',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56438479/

相关文章:

javascript - 通过 API post 请求将数十万个 JSON 对象发送到数据库

javascript - 使用 jQuery/cheerio 访问脚本标签中的变量

node.js - 如何从 Mongoose 查询结果中省略字段?

linux - 在linux上启动了两个 Node 实例

Angular 2条件Validators.required?

reactjs - NextJS 中间件功能未在区域中触发

angularjs - 如何等待 Angular2 处理动态多个 Http 请求?

css - FontAwesome 为什么图标以 SVG 格式呈现?

typescript - 编译时未定义的 TypeScript 枚举

基于第一个参数的函数参数动态类型