最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - reactJS and reading a text file - Stack Overflow

programmeradmin8浏览0评论

I have a reactJS application where I need to read in a large text file and use the data from the file to populate some arrays. I came across some code examples and I am trying to implement this code:

        readTextFile = file => {
        var rawFile = new XMLHttpRequest();
        rawFile.open("GET", file, false);
        rawFile.onreadystatechange = () => {
            if (rawFile.readyState === 4) {
                if (rawFile.status === 200 || rawFile.status == 0) {
                    var allText = rawFile.responseText;
                    console.log("allText: ", allText);
                    this.setState({
                        fundData: allText
                    });
                }
            }
        };
        rawFile.send(null);
    };

The code is called by executing this line of code:

this.readTextFile("../text/fund_list.txt");

When I execute the application, I get the following error message:

GET http://localhost:8080/text/fund_list.txt 404 (Not Found)

This is what my application structure looks like:

The readTextFile function is in the account_balanc.js code and I am trying to read in the text file /text/fund_list.txt. The file does exist so obviously I am not referencing the file correctly but I don't know why.

I have tried this.readTextFile("../text/fund_list.txt") and this.readTextFile("./text/fund_list.txt"); but neither worked. I even tried moving fund_list.txt into the /screens folder and changing the function call to this.readTextFile("fund_list.txt"); but I still get the 404 error message.

Any ideas why?

Thank you.

I have a reactJS application where I need to read in a large text file and use the data from the file to populate some arrays. I came across some code examples and I am trying to implement this code:

        readTextFile = file => {
        var rawFile = new XMLHttpRequest();
        rawFile.open("GET", file, false);
        rawFile.onreadystatechange = () => {
            if (rawFile.readyState === 4) {
                if (rawFile.status === 200 || rawFile.status == 0) {
                    var allText = rawFile.responseText;
                    console.log("allText: ", allText);
                    this.setState({
                        fundData: allText
                    });
                }
            }
        };
        rawFile.send(null);
    };

The code is called by executing this line of code:

this.readTextFile("../text/fund_list.txt");

When I execute the application, I get the following error message:

GET http://localhost:8080/text/fund_list.txt 404 (Not Found)

This is what my application structure looks like:

The readTextFile function is in the account_balanc.js code and I am trying to read in the text file /text/fund_list.txt. The file does exist so obviously I am not referencing the file correctly but I don't know why.

I have tried this.readTextFile("../text/fund_list.txt") and this.readTextFile("./text/fund_list.txt"); but neither worked. I even tried moving fund_list.txt into the /screens folder and changing the function call to this.readTextFile("fund_list.txt"); but I still get the 404 error message.

Any ideas why?

Thank you.

Share Improve this question asked Sep 17, 2018 at 18:31 Jonathan SmallJonathan Small 1,0793 gold badges20 silver badges53 bronze badges 2
  • Can you try "./src/text/fund_list.txt" – Sujil Maharjan Commented Sep 17, 2018 at 18:43
  • now I get this error: GET localhost:8080/src/text/fund_list.txt 404 (Not Found). But I even tried moving the fund_list.txt file into the /screens folder which is the same folder as the account_balance.js file and I also changed the function call to this.readTextFile("fund_list.txt"); I still got the 404 error – Jonathan Small Commented Sep 17, 2018 at 18:47
Add a ment  | 

6 Answers 6

Reset to default 5

I moved the fund_list.txt file into the public/text folder (after I created it) and changed the calling of the function to this.readTextFile("./text/fund_list.txt");

I saw this as a posted solution but then the post was removed (I don't know why) so I can't thank the user who posted it. But this solved my problem.

I'm assuming you are using Webpack as the bundler.

The reason you were getting a 404 Not Found is because you need to configure Webpack to bundle the file into the build folder the website is hosting.

Moving it to the /public folder worked because Webpack was configured to bundle all the files in the /public folder as it is usually the entry point of the project (since this is probably create-react-app).

Also the folks at create-react-app are smart and saw that if it was a .txt extension file, they would bundle them into a /text folder in the build file, just as any .jpg or .png files will bundle into a /images folder.

Note that a lot of files need a special webpack loader if you import them in project, but you can also use a webpack plugin to copy the file into your bundle and then read that programmatically as you are doing.

Therefore once you moved it to that folder your application could actually find it in the build folder -hosted in localhost:8080 !

Using HTML5 FileReader API you can easily read any file. Please have look at the following code:

function App() {
  const [json, setJson] = useState("");
  let fileInputRef = React.createRef();

  return (
    <div className="App">
      <p>{json}</p>
      <input
        type="file"
        ref={fileInputRef}
        style={{ display: "none" }}
        onChange={async e => {
          const reader = new FileReader();
          reader.onload = function() {
            const text = reader.result;
            setJson(text);
          };
          reader.readAsText(e.target.files[0]);
        }}
        accept=".json,application/json"
      />
      <button
        onClick={() => {
          fileInputRef.current.click();
        }}
      >
        Upload JSON file
      </button>
    </div>
  );
}

Here is a working Demo

You can use webpack raw loader and import the .txt file directly into the ponent.

First, install raw-loader:

npm i -D raw-loader

Second, add the loader to your webpack config:

// webpack.config.js
module.exports = {
  module: {
    rules: [
      {
        test: /\.txt$/,
        use: 'raw-loader'
      }
    ]
  }
}

Then, directly import .txt to your ponent:

import txt from './file.txt';

I don't have a lot of experience with pure javascript applications, I usually use a rails backend, but I would remend focusing on just being able to hit http://localhost:8080/text/fund_list.txt in a browser and get a response. Once you solve that it looks like the javascript will do it's thing.

Try...

const file = require("../text/fund_list.txt");

Then

this.readTextFile(file);
发布评论

评论列表(0)

  1. 暂无评论