Reputation: 7746
I have a section of code in javascript that looks like this:
var fs = require('fs');
var subscriptions = []
var array = fs.readFileSync('optimal.csv', 'utf8').toString().split("\r");
for (i in array) {
stock = array[i].split(':')[0];
if (stock)
subscriptions.push(stock)
}
When I say:
node .\realtime.js
it has no problem reading the file 'optional.csv'.
However, if I copy the same section of code to a react.js
application built with create-react-app
and try to run it, I get errors:
TypeError: fs.readFileSync is not a function
when I run it thus:
npm run start
var fs = require('fs');
// Grid data as an array of arrays
const quoteList = [];
var i = 0;
var stock;
var array = fs.readFileSync('optimal.csv').toString().split("\r");
for (i in array) {
stock = array[i].split(':')[0];
if (stock)
quoteList.push(stock)
}
.csv
file from a purely react application?Upvotes: 0
Views: 2195
Reputation: 2343
fs
is a module implemented by node.js
which is not provided by javascript
itself. Maybe other environments provide fs
as well, but react
is just a module like fs
, rather than another environment, so it can not provide extra module
Another thing, react
code run in browser, where you expect fs
refer to? Read every user's file system?
If you want to read your local csv file. You can use some bundler like Webpack which can bundle csv file into your output Javascript file. If reading local csv is what you want, you can do some thing like
const csv =require('/path/to/csv')
Maybe you need some plugin, because create-react-app
may not provide the csv loader
Here are the steps to get a json
from the csv file
npm run eject
in the project rootnpm install --save dsv-loader
webpack.config.dev.js
under config
module>loaders>exclude(line 110)
add /\.csv$/
in the list{test: /\.csv$/,loader: 'dsv-loader'}
entry in module>loaders
npm start
require('path/to/csv')
will return jsonwebpack.config.prod.js
if you need the production bundle Upvotes: 1