zoukankan      html  css  js  c++  java
  • 从「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.

  • 相关阅读:
    源码安装jdk
    yum操作的一些笔记
    Tomcat笔记
    源码编译安装zabbix server端和agent端
    用nginx做反向代理时 通过设置让后台真实服务器日志记录客户端的IP
    LVS负载均衡的两种调度模式:NAT和DR
    nginx配置文件详解
    FPGA高级设计——时序分析和收敛(转)
    12个有趣的C语言面试题
    LDO稳压器工作原理
  • 原文地址:https://www.cnblogs.com/twodog/p/12136464.html
Copyright © 2011-2022 走看看