本文章是一邊看着
《狼書:更了不得的Node.js》
一邊寫的,會有本身學習中遇到的問題,也會有書中的一些知識
"use strict" console.log("Hello world");
$ node helloworld.js > Hello World
node 命令和 console.log函數的差異在於: console.log須要再瀏覽器的控制檯中查看,而nodejs是直接在終端輸出。javascript
Nodejs 是基於CommonJS規範實現的,每個文件都是一個模塊,每一個模塊代碼都要遵照CommonJS規範, 多個文件之間的調用的核心也是基於模塊的對外暴露接口和互相引用。因此學習CommonJS是很必要的。下面演示下node.js中CommonJS的寫法。
hello.js
和 hello_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_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