Uncaught TypeError: fs.readFile is not a function
Uncaught TypeError: fs.readFile is not a function
Node.js, Webpack
在这个项目中使用了webpack,这里安装了FS。
这段代码需要读取文件,但是returns错误"Uncaught TypeError: fs.readFile is not a function"
const bookForm = document.querySelector(".book-form");
const select = document.querySelector(".select"); const fs = require("fs");
export function abc() { bookForm.addEventListener("submit", e => {
console.log(select.options[select.selectedIndex].text);
e.preventDefault();
fs.readFile("file.txt", function(error, data) {
console.log("file read");
if (error) throw error;
console.log(data); });
}); }
无法在浏览器中导入fs
模块,因为浏览器环境无法访问用户的文件系统。 fs
仅在 Node.js 上下文(在服务器上)中可用,但在客户端(浏览器)上不可用。
如果你想从浏览器发送文件到服务器,你可以使用<input type="file">
并让用户手动select他们必须发送的文件。如果您想将服务器文件的内容发送到浏览器,您可以使用 HTTP 通信 (AJAX),或者您可以在服务器端计算的 HTML 模板中呈现它的内容。
在您的配置文件中,您可以设置上传您的 txt 文件等资产的方式。然后你只需使用 require('file.txt') 来加载它——不需要使用 fs.
Node.js, Webpack
在这个项目中使用了webpack,这里安装了FS。 这段代码需要读取文件,但是returns错误"Uncaught TypeError: fs.readFile is not a function"
const bookForm = document.querySelector(".book-form");
const select = document.querySelector(".select"); const fs = require("fs");
export function abc() { bookForm.addEventListener("submit", e => {
console.log(select.options[select.selectedIndex].text);
e.preventDefault();
fs.readFile("file.txt", function(error, data) {
console.log("file read");
if (error) throw error;
console.log(data); });
}); }
无法在浏览器中导入fs
模块,因为浏览器环境无法访问用户的文件系统。 fs
仅在 Node.js 上下文(在服务器上)中可用,但在客户端(浏览器)上不可用。
如果你想从浏览器发送文件到服务器,你可以使用<input type="file">
并让用户手动select他们必须发送的文件。如果您想将服务器文件的内容发送到浏览器,您可以使用 HTTP 通信 (AJAX),或者您可以在服务器端计算的 HTML 模板中呈现它的内容。
在您的配置文件中,您可以设置上传您的 txt 文件等资产的方式。然后你只需使用 require('file.txt') 来加载它——不需要使用 fs.