本文章是一边看着
《狼书:更了不得的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