“第一个参数必须是字符串或缓冲区”-遵循w3schools的Node.js教程时出现错误

时间:2018-08-05 22:52:55

标签: javascript node.js

我正计划学习如何使用Node.js设置自己的Web服务器。 我遵循了w3schools的Node.js教程,在进入“ Node.js文件系统”部分之前一切都还不错。 (我知道,在本教程的“开始”部分。)


任务是制作两个文件。

  1. demofile1.html
<html>
<body>
<h1>My Header</h1>
<p>My paragraph.</p>
</body>
</html>
  1. demo_readfile.js
var http = require('http');
var fs = require('fs');
http.createServer(function (req, res) {
  fs.readFile('demofile1.html', function(err, data) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.write(data);
    res.end();
  });
}).listen(8080);

很简单,对吧?该.js文件应该读取.html文件中的内容,并将其显示在您的浏览器中。

在同一教程的先前示例中,我只是使用node whatever.js加载了what.js,并在浏览器中使用localhost:8080来顺利运行脚本,但是在这种情况下,chrome我出现“无法访问此站点(ERR_CONNECTION_REFUSED)”,它使node.js崩溃,并显示以下错误:

_http_outgoing.js:642
    throw new TypeError('First argument must be a string or Buffer');
    ^

TypeError: First argument must be a string or Buffer
    at write_ (_http_outgoing.js:642:11)
    at ServerResponse.write (_http_outgoing.js:617:10)
    at ReadFileContext.callback (/home/eddo/nodejs_test/demo_readfile.js:6:9)
    at FSReqWrap.readFileAfterOpen [as oncomplete] (fs.js:420:13)

我试图无济于事地res.write(data.toString());,将其更改为console.log(data);后,控制台输出为:

undefined
undefined

但至少没有给我一个“无法访问此站点(ERR_CONNECTION_REFUSED)”的信息。


我尝试过尽可能地描述性,但是英语不是我的母语,甚至不是第二语言,这是我第一次发布问题,因此,如果对某些事情不清楚,我感到抱歉,并过度解释其他人。

1 个答案:

答案 0 :(得分:1)

您的文件路径已关闭:

fs.readFile('demofile1.html', function(err, data) {

节点在主目录而不是当前目录中寻找'demofile1.html'。改为使用

fs.readFile('./demofile1.html', function(err, data) {

或更好:

fs.readFile(__dirname + '/demofile1.html', function(err, data) {