从「Hello World」说起

标签: node模块


从一个简单「hello world」程序对 node.js 有个感性的认识。

const http = requier ('http');
const pathname = '127.0.0.1';
const port = 9090;
http.createServer((req,res) => {
    res.writeHead(200,{'Content-type':'text/plan'});
    res.end('Hello World');
}).listen(port, hostname, ()=>{
    consloe.log(`Server running at http://${hostname}:${port}/`)
})
复制代码

我们从第一句代码看看到底涉及了多少核心模块,让我们开启 node.js 源码分析之旅吧。

主体代码:

http.createServer((req,res) => {
    res.writeHead(200,{'Content-type':'text/plan'});
    res.end('Hello World');
}).listen(port, hostname, ()=>{
    consloe.log(`Server running at http://${hostname}:${port}/`)
})
复制代码
  • 首先了解一下HTTP Server的继承关系,有利于更好的理解代码。

这就又涉及了 event和net模块。 最后一句:

console.log(`Server running at http://${hostname}:${port}/`);
复制代码

这里用到了 console模块,但却没有通过 require 获取,这就要说到global对象了,Node.js的顶层对象。这里笔者先卖个关子,后面会在 global 章节中详细讲述.

如果想查看 node 的一些调试日志,可以通过设置 NODE_DEBUG 环境变量,比如:

NODE_DEBUG=HTTP,STREAM,MODULE,NET node http.js
复制代码

查看 V8的日志

node --trace http.js
复制代码

总结

一个简单的 hello world 程序却涉及了多个模块,背后却是 Node社区智慧的结晶,在 web服务,异步 IO 上的高度抽象。真所谓大道至简!

下面以Linus Torvalds的一句名言来开启Node.js的源码之旅吧。

Talk is cheap, show me the code.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值