【问题标题】:NodeJS throw new TypeErrorNodeJS 抛出新的 TypeError
【发布时间】:2013-12-28 11:20:31
【问题描述】:

当我尝试运行我的 JS 文件时出现此错误:

http.js:783
    throw new TypeError('first argument must be a string or Buffer');

我正在关注这个似乎没有提到问题Tutorial Link的教程

我的 JS 文件有:

var http = require('http'),
    fs = require('fs'),
    sanitize = require('validator').sanitize;

var app = http.createServer(function (request, response) {
    fs.readFile("client.html", 'utf-8', function (error, data) {
        response.writeHead(200, {'Content-Type': 'text/html'});
        response.write(data);
        response.end();
    });
}).listen(1337);

var io = require('socket.io').listen(app);

io.sockets.on('connection', function(socket) { 
    socket.on('message_to_server', function(data) { 
        var escaped_message = sanitize(data["message"]).escape();
        io.sockets.emit("message_to_client",{ message: escaped_message }); 
    });
});

我的 node_modules 文件夹中安装了 Socket.io 和验证器。我对这类东西很陌生,看起来这个教程不是一个好的开始选择,我似乎无法让它工作。

【问题讨论】:

标签: javascript node.js


【解决方案1】:

您没有进行任何错误检查,我敢打赌readFile 正在引发错误。这意味着data是未定义的,所以当你尝试response.write(data)时,http模块会抛出一个错误。

始终检查回调函数中的错误参数,并适当处理。

fs.readFile("client.html", 'utf-8', function (error, data) {
    if (error) {
        response.writeHead(500, {'Content-Type': 'text/html'});
        response.write(error.toString());
    } else {
        response.writeHead(200, {'Content-Type': 'text/html'});
        response.write(data);
    }
    response.end();
});

【讨论】:

  • 啊,我现在遇到了一个更有用的错误Error: ENOENT, open 'client.html'
  • @Dave: ENOENT 表示找不到文件。
  • 我知道但请看这里:5.77.44.77/~civilian/socketio 它肯定在那里 =/
  • Node 可能无法按照您的预期解析路径。路径是相对于当前工作目录 解析的,而不是脚本文件所在的位置。尝试使用__dirname -- __dirname + '/client.html'
  • 我已经更改它不确定它是否有效,因为当我再次运行 js 文件时,我得到了Error: listen EADDRINUSE,我不知道如何释放端口以再次运行它。 =/
猜你喜欢
  • 1970-01-01
  • 2014-09-01
  • 2011-10-03
  • 2016-11-18
  • 1970-01-01
  • 1970-01-01
  • 2016-08-04
  • 2020-08-13
  • 1970-01-01
相关资源
最近更新 更多