Ivan
Ivan

Reputation: 7746

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)
    }

Upvotes: 0

Views: 2195

Answers (1)

Guichi
Guichi

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

  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

Upvotes: 1

Related Questions