Node.js运行报错ReferenceError: readFile is not defined求助
解决ReferenceError: readFile is not defined错误
出现这个错误的核心原因是:readFile并非全局可用函数,它是Node.js内置fs(文件系统)模块的方法,你的代码未引入该模块,导致运行时无法识别这个函数。
修复方式有两种,根据需求选择即可:
方案1:引入完整fs模块
在代码顶部添加fs模块的引入语句,调用时通过fs.readFile访问方法:
const express = require("express"); const fs = require("fs"); // 引入fs模块 const app = express(); app.get("/", (request, response) => { fs.readFile("./home.html", "utf8", (err, html) => { if (err) { response.status(500).send("sorry, out of order"); } response.send(html); }); }); app.listen(process.env.PORT || 3000, () => console.log("http://localhost:3000") );
方案2:解构引入readFile方法
如果只需要readFile这一个方法,可以直接从fs模块中解构引入,调用时无需加fs.前缀:
const express = require("express"); const { readFile } = require("fs"); // 解构获取readFile const app = express(); app.get("/", (request, response) => { readFile("./home.html", "utf8", (err, html) => { if (err) { response.status(500).send("sorry, out of order"); } response.send(html); }); }); app.listen(process.env.PORT || 3000, () => console.log("http://localhost:3000") );
进阶优化:使用Promise版本的readFile
Node.js提供了fs/promises模块,支持用async/await编写更易读的异步代码,示例如下:
const express = require("express"); const { readFile } = require("fs/promises"); // 引入Promise版readFile const app = express(); app.get("/", async (request, response) => { try { const html = await readFile("./home.html", "utf8"); response.send(html); } catch (err) { response.status(500).send("sorry, out of order"); } }); app.listen(process.env.PORT || 3000, () => console.log("http://localhost:3000") );
内容的提问来源于stack exchange,提问作者Shanxx
相关产品推荐
相关产品推荐

