关于Node.js
Node.js 是一个基于 Chrome V8 引擎的 JavaScript 运行环境。Node.js使用了事件驱动、无阻塞I/O的模型,使其轻量而且高效。因此Node.js被用来构造可伸缩的网络应用程序。
我们来看下面的例子,以下程序实现的功能是最简单的,即打印出“Hello world”。
const http = require('http');
const hostname = '127.0.0.1';
const port = 1337;
http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello World\n');
}).listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
在上面的例子中,许多链接可以被同时处理。没来一个链接请求,回调函数会被调用一次,如果没有工作的话node将处在睡眠中。
基于以上一点,与现在那些通过操作系统线程实现并发的模型对比发现,基于线程的网络应用效率相对低下并且使用也相对比较复杂。进一步来说,Node用户不用担心进程死锁——因为Node没有使用锁。而且在Node中几乎没有一个方法是直接去操作I/O的,因此进程永远不会被阻塞。正是因为Node不会被阻塞,因此经验少的程序员同样也可以开发出可伸缩的系统。
受Ruby’s Event Machine 或者 Python’s Twisted 等系统的影响,Node 在设计上和这些系统很相似,Node采用事件模型,将事件轮询作为了语法结构而不是作为应用库。在其他的系统中是通过阻塞调用开始事件轮询,典型的一个应用就是在脚本开始的时候通过回调函数定义一个行为,并且在脚本结束的时候再次通过类似于EventMachine::run()的阻塞调用开启一个服务。在Node中没有start-the-event-loop 的调用,只是执行完输入脚本以后就开始进入事件轮询了,当再没有回调函数执行的时候退出轮询。这种方式就像浏览器的javascript——事件轮询对于用户来说是透明的。
以上翻译自Nodejs官网。原文网址:https://nodejs.org/en/about/
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
如何在 JavaScript 中合并两个数组而不出现重复的情况
发布时间:2024/03/23 浏览次数:86 分类:JavaScript
-
本教程介绍了如何在 JavaScript 中合并两个数组,以及如何删除任何重复的数组。