简体   繁体   中英

Differences between Node.js and React.js applications

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)
    }
  • What is the correct way to read a .csv file from a purely react application?

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

  1. npm run eject in the project root
  2. npm install --save dsv-loader
  3. open webpack.config.dev.js under config
  4. under module>loaders>exclude(line 110) add /\\.csv$/ in the list
  5. add {test: /\\.csv$/,loader: 'dsv-loader'} entry in module>loaders
  6. re-run npm start
  7. require('path/to/csv') will return json
  8. do the same thing on webpack.config.prod.js if you need the production bundle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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