从项目中读取文本文件

Reading text file from project

我正在尝试使用 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

扩展您不能在浏览器中使用 fs 的注释,因为它适用于服务器端 nodejs。

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

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

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

  3. 使用

  4. 将 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