Webpack nodejs fs.readFile is not a function
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.
gamer
Updated on July 04, 2021Comments
-
gamer almost 3 years
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 functionI have installed
fs
usingnpm install --save fs
Also when I print
fs
it gives me empty object. Above I have doneconsole.log(fs)
it is giving me empty objectWhat is wrong in here?