【问题标题】:Reading text file from project [duplicate]从项目中读取文本文件[重复]
【发布时间】:2019-06-18 00:59:52
【问题描述】:

我正在尝试使用 fs 从我的 Angular 项目(Node 版本 v10.15.3,Angular 7)中读取一个文本文件。

我使用以下命令安装了 fs 库:

npm install --save fs
function readFile(){
const fs = require('fs');
var text = fs.readFile("src/assets/js/utile/groovy.txt", "utf8", (err, data) => {
if (err) { console.log(err) }
console.log(data);
})

这是我的错误信息:Uncaught TypeError: fs.readFile is not a function

【问题讨论】:

  • fsserver 的 Node 库,而不是 client。部署应用时,您希望该文件在哪里?
  • 好的@jonrsharpe。那么关于如何做到这一点的任何解决方案?谢谢
  • 使用 HTTP 请求读取您的文档,例如 here
  • 好的@youri 让我看看你的链接,然后回到你身边

标签: node.js angular fs


【解决方案1】:

在 cmets 上进行扩展,您不能在浏览器中使用 fs,因为它适用于服务器端 nodejs。

另一种方法是使用 HTTP 请求来检索您的文本文档。这样做的好处是能够将此文本文档托管在其他位置,例如 github 或其他文件托管服务。

  1. 将文本文件放在 /assets 文件夹中

  2. 确保 HttpClientModule 已导入您的 app.module.ts 文件中

  3. 将 HTTPClient 注入到您的组件或服务中

public constructor(
  private http: HTTPClient,
) {}
  1. 请求您的文件
this.http.get('/assets/groovy.txt')
  .subscribe((data) => {
    console.log(data);
  },
  (err: HttpErrorResponse) => {
    if (err.error instanceof Error) {
      // A client-side or network error occurred. Handle it accordingly.
      console.log('An error occurred:', err.error.message);
    } else {
      // The backend returned an unsuccessful response code.
      // The response body may contain clues as to what went wrong,
      console.log(`Backend returned code ${err.status}, body was: ${err.error}`);
     }
    }
  );

延伸阅读:https://angular.io/guide/http

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-14
    • 1970-01-01
    • 1970-01-01
    • 2016-08-04
    • 2013-08-29
    • 2021-05-16
    • 1970-01-01
    • 2012-07-03
    相关资源
    最近更新 更多