【发布时间】:2021-07-30 11:37:20
【问题描述】:
我正在尝试将 html 文件读取到我的 .js 文件中。我正在使用var fs = require('fs'); 读取文件,当我在终端中运行时,它会执行,但是当我浏览到本地主机时,我在终端中收到此错误:
http_outgoing.js:722
throw new ERR_INVALID_ARG_TYPE('first argument',
^
TypeError [ERR_INVALID_ARG_TYPE]: The first argument must be of type string or an instance of Buffer or Uint8Array. Received undefined
at write_ (_http_outgoing.js:722:11)
at ServerResponse.write (_http_outgoing.js:687:15)
at ReadFileContext.callback (/Users/mac/test/demo_readfile.js:20:9)
at FSReqCallback.readFileAfterOpen [as oncomplete] (fs.js:282:13) {
code: 'ERR_INVALID_ARG_TYPE'
}
并且浏览器中的错误是“本地主机没有发送任何数据”。我只能假设本地主机找不到文件,或者无法打开它。 HTML 文件保存在与 .js 文件相同的文件夹中。这是.js文件代码:
var http = require('http');
var fs = require('fs');
''''''''''''''''''''''''''''''''''''''''''''''''''''''
http.createServer(function (req, res) {
//Open a file on the server and return its content:
fs.readFile('/demofile1.html', function(err, data) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
return res.end();
});
}).listen(8080);
和 HTML 代码
<html>
<body>
<h1>My Head</h1>
<p>my paragraph</p>
</body>
</html>
【问题讨论】:
-
嘿@Strawberry Raen,我看到你要求推荐学习node.js。如果您是 Node.js 的新手,那么我会推荐 Samer Buna 在 PluralSight 上关于 node.js 的课程。他解释了原始 node.js,而不是直接跳到如何使用第三方库。顺便说一句,我不隶属于他。祝你学习 NodeJs 好运。
-
谢谢你我去看看他
标签: node.js