React.js 从本地文件读取

lve*_*lve 5 fs node.js reactjs

我目前在我的应用程序中使用与节点 js 的反应。

我试图从文本文件中读取,当我尝试不同的事情时会得到不同的错误。通过研究,从文件读取的最简单路径是使用“fs”,因此我将发布我尝试从本地文件(客户端)读取的两种方法。

如果有人可以帮助解决我的错误,或者甚至向我展示从本地文件中读取的不同方式,我将不胜感激!

import React ...
import { readFile, readFileSync } from 'fs';
// other imports

class Background extends Component {
     // my constructor

     componentDidMount() {
         this.loadMe();
     }

     loadMe() {
          var file = './read_file';

          /* WAY 1: Asynchronously using readFile */
          readFile(file, function(err, data) {
               if (err) { console.log(err) }
               console.log(data);
          }

          /* WAY 2: Synchronously using readFileSync */
          var data = readFileSync(file);
          console.log(data);
     }
}
Run Code Online (Sandbox Code Playgroud)

显然,我不会同时运行两种方式。我还基本上从其他堆栈溢出答案和一些在线教程中复制了代码。我查看了FileReader但无法使其工作。

我目前收到的错误:TypeError: Object(...) is not a function 指向var data = readFileSync(file);

谢谢!

Mos*_*ini 2

fs是一个为服务器 JS env(如 NodeJS)保留的库。

  • @MosèRaguzzini,你误导了......确实可以从客户端的文件中读取。只是不带“fs”。有时,错误的答案比没有答案更糟糕。 (3认同)