fs 仅适用于服务器,不适用于客户端。浏览器没有(一般)访问文件系统的权限。
有几种选择:
1。公共文件夹
将.csv文件放入public文件夹,然后你可以像这样加载它:
function App() {
const [ text, setText ] = useState();
const load = function(){
fetch( './csvInPublicFolder.csv' )
.then( response => response.text() )
.then( responseText => {
setText( responseText );
})
};
return (
<div>
<button onClick={ load }>load</button>
<h2>text:</h2>
<pre>{ text }</pre>
</div>
);
}
2。 webpack 文件加载器
或者,如果文件必须在 src 文件夹内,
- 安装:
yarn add file-loader --dev
- 添加
webpack.config.js:
module.exports = {
module: {
rules: [
{
test: /\.csv$/,
use: [
{
loader: 'file-loader',
},
],
},
],
},
};
import csvFilePath from './csvInSrcFolder.csv';
import { useState } from 'react';
function App() {
const [ text, setText ] = useState();
const load = function(){
fetch( csvFilePath )
.then( response => response.text() )
.then( responseText => {
setText( responseText );
});
};
return (
<div>
<button onClick={ load }>load</button>
<h2>text:</h2>
<pre>{ text }</pre>
</div>
);
}
3。服务器
或者您可以创建自定义 server.js 并向服务器发送请求。在服务器上,您可以访问文件系统 (fs)。
4。解析csv
如果您不想自己解析文件内容,可以使用现有的 csv 解析器。有人推荐papaparse(我没有自己的经验关于哪些好)
import * as Papa from 'papaparse';
// ...
fetch( csvFilePath )
.then( response => response.text() )
.then( responseText => {
// -- parse csv
var data = Papa.parse(responseText);
console.log('data:', data);
});