Node.js抛出一个未处理的错误事件

Node.js throws er Unhandled error event

本文关键字:未处理 一个 错误 事件 js Node      更新时间:2023-09-26

我已经在Centos 6服务器上安装了node, npm,并且我正在使用putty在服务器上运行命令。

Node被正确地安装在根目录下,并且在服务器的任何地方都运行得很好。

我的项目是在/home/shaadise/public_html/icon

我已经创建了一个hello.js文件/home/shaadise/public_html/icon

var http = require('http');
http.createServer(function (request, response) {
    response.writeHead(200, {'Content-Type': 'text/plain'});
    response.end('Hello World'n');
}).listen(8080);
console.log('Server started');

运行js:

root@vps [/home/shaadise/public_html/Ikon]# node hello.js
Server started
events.js:72
        throw er; // Unhandled 'error' event
              ^
Error: listen EADDRINUSE
    at errnoException (net.js:904:11)
    at Server._listen2 (net.js:1042:14)
    at listen (net.js:1064:10)
    at Server.listen (net.js:1138:5)
    at Object.<anonymous> (/home/shaadise/public_html/Ikon/hello.js:6:4)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Function.Module.runMain (module.js:497:10)
root@vps [/home/shaadise/public_html/Ikon]#  throw er; // Unhandled 'error' event
-bash: throw: command not found
-bash: //: is a directory

问题:我必须把我的节点js文件,我怎么能访问它????

我测试运行命令:

root@vps [/home/shaadise/public_html/Ikon]# netstat -plnt | grep ':8080'
tcp        0      0 0.0.0.0:8080                0.0.0.0:*                   LISTEN      27111/nginx

Error: listen EADDRINUSE明确表示您或守护进程正在8080上运行另一个应用程序。

但是,要检查,请尝试在不同的端口上运行?

-edit- 因为这得到了相当多的支持,我想我应该添加一些额外的调试到它。

几乎所有node.js教程默认使用8080端口运行。这是因为它与其他web服务(如Apache或NGinX)使用的默认端口80相似。

为了确定是否有其他应用程序在同一端口上运行,您可以使用netstat -a查看所有活动连接及其端口,然后grep该列表以查找与Node.js应用程序在同一端口上连接的任何进程。

您的Node应用程序运行在哪个端口上并不重要,只要它是一个空闲端口即可。最终,当你部署到生产环境时,你将同步你正在使用的任何内容服务器(Apache/NGinX)来使用相同的端口。

出现此错误的常见情况是:

  1. 启动
  2. 使用Ctrl+z把它放到背景
  3. 尝试再次启动

的好方法是总是尝试先按Ctrl+c,这将向应用程序发送信号(它可能决定关闭)。你可以在这里阅读更多内容:在shell中Ctrl-z和Ctrl-c有什么区别?

服务器正在后台运行;通常情况下,当你不终止这个过程时,它就会发生。为了解决这个问题,你可以在终端上输入:

ps | grep 'node'

这段代码将显示一个具有特定编号的进程,使用下一段代码终止该进程:

kill -9 "specific number"

如果不能正常工作,可以使用sudo

如果您使用的是基于Linux的系统,首先您必须列出所有使用该特定端口的程序并杀死它们(意思是停止它们)

示例:我想列出所有使用3000端口的程序
fuser 3000/tcp 

然后选择进程ID,它位于获得的文本行右侧,并发出kill命令

示例:如果进程ID的值为2345,则命令将为

kill 2345

如果关闭正在使用该端口的进程不能解决问题,请尝试以下解决方案:

安装下面的包为我解决了这个问题。

npm install ws@3.3.2 --save-dev --save-exact

在终端运行以下命令:

echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p

对于Arch Linux,将这一行添加到/etc/sysctl.d/99-sysctl.conf:

fs.inotify.max_user_watches=524288

然后执行:

sysctl --system

https://github.com/guard/listen/wiki/Increasing-the-amount-of-inotify-watchers技术细节