Webpack nodejs fs.readFile 不是函数

Webpack nodejs fs.readFile 不是函数

问题描述:

我有一个 webpack 配置,如:

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"
    }
};

我想使用 fs

我正在做类似的事情:

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 不是函数

我已经使用 npm install --save fs

此外,当我打印 fs 时,它给了我空对象.上面我已经完成了 console.log(fs) 它给了我空对象

Also when I print fs it gives me empty object. Above I have done console.log(fs) it is giving me empty object

这里有什么问题?

我相信提到的评论,

node: { fs: "empty" }

需要删除.此外,您的所有代码都必须在服务器上运行.您无法在浏览器中读取此类文件.节点 API 仅适用于服务器端,因此您需要使用 express 或一些类似的库构建 API例如

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);
        }) 
    })

然后在您的浏览器中,您需要使用 AJAX 来调用 API 并检索文件内容.

Then in your browser you would need to use AJAX to call the API and retrieve the file contents.

读取任意文件具有明显的安全问题.您不应该允许 api 读取用户喜欢的任何文件.您应该非常小心地限制输入并限制可用的文件集.

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.