初學nodejs (一):nodejs 入門

本文章是一邊看着 《狼書:更了不得的Node.js》一邊寫的,會有本身學習中遇到的問題,也會有書中的一些知識

Hello Node.js !

最簡單的例子
  • 建立 helloworld.js, 代碼以下。
"use strict"
    console.log("Hello world");
  • 在終端中執行
$ node helloworld.js
    > Hello World

node 命令和 console.log函數的差異在於: console.log須要再瀏覽器的控制檯中查看,而nodejs是直接在終端輸出。javascript

Hello CommonJS

Nodejs 是基於CommonJS規範實現的,每個文件都是一個模塊,每一個模塊代碼都要遵照CommonJS規範, 多個文件之間的調用的核心也是基於模塊的對外暴露接口和互相引用。因此學習CommonJS是很必要的。下面演示下node.js中CommonJS的寫法。
  • 建立兩個文件夾: hello.jshello_test.js
// hello.js
    module.exports = function(){
        console.log("Hello CommonJS!");
    }
    
    // hello_test.js
    const hello = require("./hello.js");
    
    hello();
  • 執行
$ node hello_test.js
    > Hello CommonJS!

Hello HTTP

  • 新建 hello_node.js
// "hello_node.js"
    "use strict"
    const http = require('http');
    
    http.createServer((req, res)=>{
        res.writeHead(200, {'Content-Type': 'text/plain'});
        res.end('Hello Node.js!');
    }).listen(3000, "127.0.0.1");
    
    console.log("Server running at http://127.0.0.1:3000/");
  • 啓動服務
$ node hello_node.js
    > Server running at http://127.0.0.1:3000/
上面代碼的知識點:
引用了Node.js SDK內置的名爲 http的模塊
經過 http.createServer建立了一個HTTP服務
經過 listen方法制定服務運行的 端口 和 IP 地址
req: 全寫 request,是瀏覽器發送過來的請求信息。 res:全寫response,是返回給瀏覽器請求的信息

短短的幾行,咱們的HTTP的服務就跑起來了,真的是好簡單啊。java

圖片描述

下一篇:初學nodejs (二):用vscode斷點調試咱們的代碼node

相關文章
相關標籤/搜索