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.

  • 相关阅读:
    校外实习-7.28
    校外实习-7.27
    校外实习-7.26
    校外实习-7.25
    校外实习-第三周总结
    校外实习-7.22
    校外实习-7.21
    校外实习-7.20
    作业九—总结
    结对编程项目---四则运算(截图总结篇)
  • 原文地址:https://www.cnblogs.com/twodog/p/12136466.html
Copyright © 2011-2022 走看看