nodeJs 从浅入深
什么是nodeJS?不瞎扯了,基于事件驱动的服务器端的编程语言,暂时这么理解;nodeJs是JavaScript的一个运行环境,石川大神说nodeJS比PHP快80倍,我暂时相信了;
了解一门语言,先了解数据结构,这个跟浏览器端的js区别不大,也就是某些顶层对象(如window,在nodeJs中是没有的)有些区别;
作为一门后端语言:如何构建web服务器呢?你需要从头开始了解http?(no,有自带的nodejs http模块);类似这样,nodeJs帮我们封装了需要常用的模块;
http模块:http请求服务 如: createServer()
fs模块:文件读写, 如:readFile()
url模块: parse(url,true) ;解析url;
querystring模块: parse(str) 解析查询字符串==>{ }
有了上述几个模块,可以用了搭建简单的服务器:
先来一个最简单的服务器: server.js如下:
const http = require("http");
const fs=require('fs');
var server=http.createServer(function(req,res){
//http模块的 createServer()方法用于创建一个http服务:
//参数: req,响应请求:
//参数: res,返回应答:
res.write("hello nodejs");
res.end();
//这一步在浏览器localhost:8898打开可以看到 hello nodejs(当然前提是node 运行一下文件);
----分割线---
//但是这个服务器太low了,通常服务器都是可以返回文件的: 假设注释掉上面连行代码: 我们来看看req的用法:
//假设我们在浏览器输出 localhost:8898/index.html 想当然我们是把这个页面返回给客户端;怎么做呢?
//req对象中,我们可以截取到 /index.html
var url=req.url // index.html 当然如果后面有参数也是可以截取到的
//现在我们假设有一个www目录在 server.js的同级目录,www下新建 index.html ,页面内容自定义:
//通常的想法是:
if(url=='index.html'){
fs.readFile("www/index.html",function(err,data){
if(err){
console.log("文件读取出错..")
}else{
res.write(data) //读取html内容页面,并返回给前端;
}
res.end()
})
}
if(url=="regester.html"){---codoe---}
//就像上面这样完成了一系列页面的请求; ---就如一个系统有数百个页面,这种方式就彻底over了,看下面方式
});
server.listen(8898)
一个服务器统一读文件和接口
const http = require("http");
const urlLib = require('url');
const fs = require('fs');
const querystring = require('querystring');
// console.log(querystring.parse("username=liuhf&password=123456"));
var server = http.createServer(function (req, res) {
var obj = urlLib.parse(req.url, true);
var path = obj.pathname; //pathname; host到? 前面之间的str
var GET = {}; //测试get数据;
var POST = {}; //测试post数据;
if (path == '/favicon.ico') { return } //chrome 浏览器会自动请求站点图标;
GET = obj.query;
var data_str = ''; //暂时存放简单数据;
//作为一个服务器,最基本的具有 处理 文件请求 和 接口请求
if (path.indexOf("api") < 0) { //是文件请求 //这里只是简单的举一个例子;
//文件服务器:
fs.readFile("./www" + path, function (err, data) { //相当于一个统一的映射到www目录;
if (err) {
console.log(err);
} else {
res.write(data)
}
res.end();
});
} else {
console.log("请求接口--")
//接口请求:
req.on("data", function (data) { //仅对post数据有效;
data_str += data; //当post数据过大的时候,会分次传输送;
console.log("post_data",data)
});
req.on("end", function (data) { //end '事件' 并不是post独有,不管有没有post数据,都会进入这里;
POST = querystring.parse(data_str)
console.log("post提交--")
console.log("GET:",GET);
console.log("POST:",POST)
res.end();
});
}
}).listen(8899);

浙公网安备 33010602011771号