Reputation: 1551
I want to read and write a file using NodeJS default fs module. I've almost tried everything I can find on the internet. ES6 and CommonJS examples, editing the Webpack.config file, added packages that should add Promises and so on.. But nothing seems to work out.
Currently this is my webpack.config.js
var webpack = require('webpack');
module.exports = {
entry: './index.js',
output: {
path: 'public',
filename: 'bundle.js',
publicPath: ''
},
node: {
fs: "empty"
},
"browser": { "fs": false },
resolve: {
modulesDirectories: ['web_modules', 'bower_components', 'node_modules']
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader?presets[]=es2015&presets[]=react'
}
]
}
}
As I've mentioned some lines suggested in this topic where added.
I want to use the fs.readFile
in the component shown below:
var React = require('react');
var fs = require('fs');
var QuestionList = React.createClass({
handleVote: function(id, state) {
var file = '../public/api/questions';
fs.readSyncFile(file, function(err, data) {
console.log( err );
console.log( data );
});
},
render() {
var rows = []
this.state.questions.forEach( function(question) {
rows.push(
<QuestionItem
onVoteUpdate={this.handleVote}
key={question.id}
up={question.upvotes} down={question.downvotes}
/>
);
}.bind(this));
return (
<section>
<ul className="question-list">{rows}</ul>
</section>
)
}
});
module.exports = QuestionList;
I've removed some functions, like loading the question with jQuery and set the InitialState
, for this example.
I'll can imagine webpack can't build any back-end tasks like FS in an front-end js file or something like that, but how is it possible to read and write files using Node, Webpack and React? Is this even possible?
Upvotes: 1
Views: 2517
Reputation: 35797
You can't use fs
in a front-end JS file, as far as I know, as you don't have access to the filesystem from the browser (it looks like you might be expecting the readFileSync
call to get run during Webpack's compilation - this isn't how it works!). You either need a Webpack loader of some kind to make it so you can require()
the file, or you'll have to load it via AJAX.
Upvotes: 1