Reputation: 5873
I have a webpack config like:
var path = require('path')
module.exports = {
entry: "./index.js",
output: {
path: path.join(__dirname, 'static'),
filename:'bundle.js'
},
module: {
loaders: [
{ test: /\.js$/, exclude: /node_modules/, loader: "babel-loader"},
{ test: /\.json$/, loader: 'json-loader' },
]
},
node: {
fs: "empty"
}
};
And I want to read a file using fs
I am doing something like:
var fs = require('fs')
console.log(fs)
fs.readFile('input.txt', function (err, buffer) {
console.log("buffer")
console.log(buffer)
})
I just want to read a file here but when I do this it gives me error saying:
fs.readFile
is not a function
I have installed fs
using npm install --save fs
Also when I print fs
it gives me empty object.
Above I have done console.log(fs)
it is giving me empty object
What is wrong in here?
Upvotes: 29
Views: 54590
Reputation: 1394
As I believe the comments mentioned,
node: { fs: "empty" }
Needs to be removed. Moreover, all your code must run on the server. You cannot read files like this in the browser. Node APIs are server-side only, so you would need to build an API using express or some similar library e.g.
router.get('/file/read', (req, res, next) => { fs.readFile('input.txt', function (err, buffer) {
console.log("buffer")
res.send(buffer);
})
})
Then in your browser you would need to use AJAX to call the API and retrieve the file contents.
Reading arbitrary files has OBVIOUS SECURITY ISSUES . You should not allow the api to read any files the user likes. You should be very careful here to restict input and limit the set of files available.
Upvotes: 4