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?
import React from 'react'; const fs = require('fs') const ToolTipTextMod = (props) => { let txt = null; fs. readFile('../../components/ToolTip/ToolTipText. txt',(err, data) => {console. log(data)}) return( <p>{txt},{props.
In fs. readFile() method, we can read a file in a non-blocking asynchronous way, but in fs. readFileSync() method, we can read files in a synchronous way, i.e. we are telling node.
unlinkSync() method is used to synchronously remove a file or symbolic link from the filesystem. This function does not work on directories, therefore it is recommended to use fs. rmdir() to remove a directory.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With