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?
Your code looks fine! So there is nothing wrong with the code. To cross verify try running the same code here https://www.tutorialspoint.com/execute_nodejs_online.php and you can see that console.log(fs);
won't be blank.
So the reason that your code is showing error is because you installed the node module named 'fs' using the command npm install --save fs
which you shouldn't! Node comes up with this module by default. All you got to do is just require is using const fs = require('fs');
(using var
, or let
is also acceptable but I will recommend const
here).
So just delete the local node_modules
folder and then run this code again by installing other modules that you want and it will run fine!
Hope this helps :)