简体   繁体   English

读取文件组件(fs.readFile)

[英]Read file component (fs.readFile)

Im getting an error stating that fs.readFile is not a function.我收到一条错误消息,指出fs.readFile不是 function。 What am I not understanding about how to use fs.readFile ?我对如何使用fs.readFile什么?

https://www.geeksforgeeks.org/node-js-fs-readfile-method/ https://www.geeksforgeeks.org/node-js-fs-readfile-method/

The objective here is to get the contents of my file into a variable and parse thought the value further.这里的目标是将我的文件的内容放入一个变量中并进一步解析该值。

import React from 'react';


const fs = require('fs')

const ToolTipTextMod = (props) => {
    let txt = null;
    fs.readFile('../../components/ToolTip/ToolTipText.txt',(err, data) => {console.log(data)})

    return(
        <p>{txt},{props.textId}</p>

    );
}

export default ToolTipTextMod;

fs is a Nodejs module. fs 是一个 Nodejs 模块。 So I would recommend using a package like raw-loader, but for that you need to have webpack setup.所以我建议使用像 raw-loader 这样的 package,但为此你需要设置 webpack。

So alternate way is to simply use fetch/Axios.所以替代方法是简单地使用 fetch/Axios。

Example:例子:

 import React, {useState,useEffect} from "react";
 import txt from "./test.txt"; // Your file path 
 import Axios from "axios"; // Import Axios or use Fetch.


const ToolTipTextMod = (props) => {
const [text,setText] = useState("");

useEffect(()=>{
   Axios(txt).then(res => setText(res.data)); // This will have your text inside data attribute
},[])

return <p>/* code */</p>

}

fs.readFile() is for NodeJs, for frontend react you can use FileReader() : fs.readFile()用于 NodeJs,对于前端反应,您可以使用FileReader()

  const handleReadFile = () => {
    const reader = new FileReader();
    reader.onload = (e) => {
      const fileContents = e.target.result;
      console.log(fileContents);
      setText(fileContents);
    };
    reader.readAsText(selectedFile);
  };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM