这是一个连续的 node 学习笔记, 本文是第一章, 会持续更新, 持续完善
python 好用, 用久了就会把人的脾气养起来, nodejs 不好用, 但效率很好, 也能彻底治好你的坏脾气
nodejs 的回调是我用过的最蛋疼的编程方式之一, 但也足够巧妙, 学好 node, 对一个程序员而言, 也是一个稳赚不赔的买卖
废话不多说, 上代码
1. 完成环境的搭建, 运行一个正则, 提取字符串中的数字
- let numRe = /\d+/g;
- console.log("123dsgfas 12434 sdfasdf234dagsdfg".match(numRe));
nodejs 的语法和浏览器 js 的语法非常接近, 安装好 node 后, 可以写个正则, 测试一下环境是否安装成功, 通过 atom 的 script 插件容易造成端口占用, 建议学习过程中用命令行工具执行 node 脚本, 如 node HelloWorld.js
2. http 模块开启一个服务
- const http = require("http")
- // 开启一个监听 8080 端口的静态服务
- http.createServer(function(req, res){
- console.log("==>", req.url);
- if (req.url === "/1.html"){
- res.write("you have request 1.html");
- }else if (req.url === "/2.html") {
- res.write("you have request 2.html");
- }else{
- res.write("404(page not found)");
- }
- res.end();
- }).listen(8080)
开启服务, 分三步:
第一步: 引入模块
第二步: 调用模块 http.createServer
第三步: 监听端口 http.createServer(function(req, res){}).listen(8080)
3. fs 模块读写文件
- const fs = require("fs");
- // 写入文件
- fs.writeFile("HelloWorld.txt", "HelloWorld HelloNode", function(err){
- if(err){
- console.log(err);
- }
- // 读取刚刚写入的数据
- else{
- fs.readFile("HelloWorld.txt", function(err, data) {
- if(err){
- console.log(err);
- }else{
- console.log(data.toString());
- }
- })
- }
- })
简单读写文件非常简单, 与其它编程语言类似, 把调用方法背过就可以了
4. 实现一个静态 http 服务器
- const http = require("http");
- const fs = require("fs")
- http.createServer(function(req, res){
- // 打开 www/ 目录下的文件
- fs.readFile("./www/"+req.url, function(err, data) {
- if(err){
- console.log(err);
- res.write("404");
- res.end();
- }else{
- console.log(data.toString())
- res.write(data);
- res.end();
- }
- })
- }).listen(8080)
通过了读取 www / 目录下的文件, 实现了静态资源服务器
5. 获取 get 数据
- const http = require("http");
- const url = require("url");
- http.createServer(function(req, res){
- let reqObj = url.parse(req.url, true)
- let urlPath = reqObj.path;
- let urlData = reqObj.query;
- let log = "==>urlPath:" + urlPath +"==>>urlData:"+ JSON.stringify(urlData);
- console.log(log);
- res.write(log);
- res.end();
- }).listen(6060)
解析 get 请求的参数
6. 获取 post 数据
- const http = require("http");
- const querystring = require("querystring");
- http.createServer(function(req, res){
- let dataStr = '';
- let i = 0;
- req.on("data", function(data){
- dataStr+=data;
- console.log(` 第 ${i++} 次收到数据 `);
- })
- req.on("end", function(){
- console.log("end");
- let parseData = querystring.parse(dataStr);
- console.log("parseData:", parseData);
- res.write(new Buffer(dataStr, "utf8"));
- res.end();
- })
- }).listen(8800)
解析 post 请求的参数
小结: 用已有知识 实现简单的服务器程序
- const http = require("http");
- const fs = require("fs");
- const querystring = require("querystring");
- /*
- *1. 访问 www 内的静态资源
- *2. 解析 get 请求, 并保存到 serverLog.txt
- *3. 解析 post 请求 serverLog.txt
- */
- // 获取当前时间
- function getNowDate(){
- let dt = new Date();
- let year = dt.getFullYear();
- let month = dt.getMonth();
- let day = dt.getDate();
- // 将月份加 1
- month = month + 1;
- // 将月份补齐到两位
- if (month <= 9){
- month = "0" + month;
- }
- // 将日补齐到两位
- if (day <= 9){
- day = "0" + day;
- }
- let hour = dt.getHours();
- let minutes = dt.getMinutes();
- let seconds = dt.getSeconds();
- return year+"-"+month+"-"+day+"-"+hour+"-"+minutes+"-"+seconds;
- }
- http.createServer(function(req, res){
- // 1. 尝试访问 www 下的静态资源
- fs.readFile("./www"+req.url, function(err, data){
- if(err){
- //2. 解析请求的参数, 并保存到 log
- if(req.method === "GET"){
- console.log("收到了 GET 请求")
- let getData = querystring.parse(req.url.split("?")[1]);
- console.log("获得的 get 数据为 ==>",getData);
- fs.writeFile("./serverLog.txt", getNowDate()+"\n"+JSON.stringify(getData)+"\n", {flag: 'a'},function(err){
- if(err){
- console.log(err);
- console.log("GET 数据保存至 log 出错");
- }
- });
- }else if (req.method == "POST") {
- console.log("收到了 POST 请求")
- let tmpData = '' req.on("data", function(data){
- tmpData+=data;
- });
- req.on("end", function(){
- let postData = querystring.parse(tmpData);
- console.log("获得的 post 数据为 ==>", postData);
- fs.writeFile("./serverLog.txt",getNowDate()+"\n"+JSON.stringify(postData)+"\n", {flag: 'a'},function(err){
- if(err){
- console.log(err);
- console.log("POST 数据保存至 log 出错");
- }
- });
- })
- }
- res.write("404");
- res.end();
- }else{
- res.write(data);
- res.end();
- }
- })
- }).listen(8000)
python 测试脚本
- import requests
- requests.get("http://127.0.0.1:8000/?name=zhaozhao&age=18&method=GET")
- requests.post("http://127.0.0.1:8000", data={"name": "zhaozhao", "age": 18, "method": "POST"})
熟悉了 nodejs 回调机制, 用原生 nodejs 写服务器程序是一件很有效率的事情 , 测试脚本还是 requests 好用!
来源: http://www.jianshu.com/p/e15e079c7e9f