【问题标题】:TypeError [ERR_INVALID_ARG_TYPE]: The first argument must be of type string or an instance of Buffer or Uint8Array. Received undefinedTypeError [ERR_INVALID_ARG_TYPE]:第一个参数必须是字符串类型或 Buffer 或 Uint8Array 的实例。收到未定义
【发布时间】: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


【解决方案1】:

您的代码似乎正确,但您的代码几乎没有错误。您的文件读取路径必须具有父文件夹的位置,或者该文件夹包含要读取的文件。你没有提到文件路径为'./'('./demofile1.html')。

试试下面的代码。

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) {
        console.log(data)
        res.writeHead(200, { 'Content-Type': 'text/html' });
        res.write(data);
        return res.end();
    });
}).listen(8080);

我的文件夹结构: [![文件夹结构][1]] [1]:https://i.stack.imgur.com/mO9hx.png

【讨论】:

  • 试过了,还是不行,一直报同样的错误。它也最喜欢它不读取数据周期?我很困惑。
  • 或者不拿起文件。或者我犯了一个我没有意识到的愚蠢的小错误。
  • 这个错误是什么意思,它在终端中突出显示:在 ReadFileContext.callback (/Users/mac/test/demo_readfile.js:21:9)
  • 如果您使用我的代码,我假设您的 server.js 和 demofile.html 文件位于同一文件夹或位置。我试用了您的代码,它运行良好,但正如我在回答中提到的,几乎没有什么变化。
【解决方案2】:

我迟到了,如果其他人正在学习 ww3 课程,我会回复。 正如错误所说, ServerResponse.write 接受一个参数作为字符串。由于函数 readfile 是异步的,因此您会获得未定义的数据,这是它的数据类型,因此您将 undefined 传递给 res.write()。为了不出现任何错误:

res.write(toString(data))

然后你会得到一个“未定义”的空白页面。这门课很老了(2011 年什么的)。我们应该转向新的东西。 Javascript 从那时起就发展起来了。

【讨论】:

    猜你喜欢
    • 2022-07-13
    • 1970-01-01
    • 2022-11-10
    • 2021-03-16
    • 2021-07-16
    • 2022-01-12
    • 2021-06-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多