本文章是一边看着
《狼书:更了不起的Node.js》
一边写的,会有自己学习中遇到的问题,也会有书中的一些知识
Hello Node.js !
最简单的例子
- 创建 helloworld.js, 代码如下。
"use strict"
console.log("Hello world");
- 在终端中执行
$ node helloworld.js
> Hello World
node 命令和 console.log函数的差别在于: console.log需要再浏览器的控制台中查看,而nodejs是直接在终端输出。
Hello CommonJS
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 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的服务就跑起来了,真的是好简单啊。