node.js入门1
参考:
Node入门 » 一本全面的Node.js教程 https://www.nodebeginner.org/index-zh-cn.html
用node.js实现简单的web服务器 - loogn - 博客园 https://www.cnblogs.com/loogn/p/3362475.html
安装:
https://nodejs.org/en/ 下载64位安装。安装完后,会添加node.js和node.js command prompt。
Hello World:
编辑一个hello.js文件,内容只有一句
console.log("Hello World");
运行
node hello.js
一个完整的基于node.js的web应用
1、服务器模块
项目的根目录下创建一个server.js
var http = require("http"); http.createServer(function(request, response) { response.writeHead(200, {"Content-Type": "text/plain"}); response.write("Hello World"); response.end(); }).listen(8888);
运行node server.js,打开浏览器访问http://localhost:8888/,浏览器会出现Hello World。
包装server.js变成模块
var http = require("http"); function start() { function onRequest(request, response) { console.log("Request received."); response.writeHead(200, {"Content-Type": "text/plain"}); response.write("Hello World"); response.end(); } http.createServer(onRequest).listen(8888); console.log("Server has started."); } exports.start = start;
创建index.js,内容
var server = require("./server"); server.start();
2、路由
改写server.js
var http = require("http"); var url = require("url"); function start() { function onRequest(request, response) { var pathname = url.parse(request.url).pathname; console.log("Request for " + pathname + " received."); response.writeHead(200, {"Content-Type": "text/plain"}); response.write("Hello World"); response.end(); } http.createServer(onRequest).listen(8888); console.log("Server has started."); } exports.start = start;
新建route.js文件
function route(pathname) { console.log("About to route a request for " + pathname); } exports.route = route;
使用依赖注入改写server.js
var http = require("http"); var url = require("url"); function start(route) { function onRequest(request, response) { var pathname = url.parse(request.url).pathname; console.log("Request for " + pathname + " received."); route(pathname); response.writeHead(200, {"Content-Type": "text/plain"}); response.write("Hello World"); response.end(); } http.createServer(onRequest).listen(8888); console.log("Server has started."); } exports.start = start;
相应的index.js也要改写
var server = require("./server"); var router = require("./router"); server.start(router.route);