querystring: --- > qs npm i qs ==> qs:parse/stringify第三方插件,只有一個參數html
JSON.parse 字符串轉對象
JSON.stringify 對象轉字符串node
qs.parse() --- decode
qs.stringify() --- encodejquery
parse/stringify(str/json,第一次切割符號,第二次切割符號)linux
qs.escape() 編碼 encodeURIComponent
qs.unescape() 解碼 decodeURIComponentajax
qs.decode 對象轉字符串
qs.encode 字符串轉對象npm
var qs = require("querystring"); var str = "a=12&b=5" //{a:12,b:5} var json = qs.parse(str); console.log(json); console.log(qs.stringify(json));
res:json
my@my-THINK MINGW64 /d/workspace/7.11 $ node qs { a: '12', b: '5' } a=12&b=5
//qs.parse/stringify(str,第一次切割的符號,第二次切割的符號)服務器
var qs = require("querystring"); var str = "a|12=b|5=age|20"; //qs.parse/stringify(str,第一次切割的符號,第二次切割的符號) var json = qs.parse(str,"=","|"); console.log(json); console.log(qs.stringify(json,"=","|"));
resapp
my@my-THINK MINGW64 /d/workspace/7.11 $ node qs3 { a: '12', b: '5', age: '20' } a|12=b|5=age|20
引入第三方模塊 npm i qsasync
//qs.parse/stringify(str) 後面不能跟分隔符號
var qs = require("qs"); var str = "a=12&b=5"; var json = qs.parse(str); console.log(json); console.log((qs.stringify(json)));
res:
my@my-THINK MINGW64 /d/workspace/7.11 $ node qs4 { a: '12', b: '5' } a=12&b=5
var qs = require("querystring"); var str = "aaa中文"; var code = encodeURIComponent(str); console.log(code); console.log(decodeURIComponent(code)); console.log("----------------------"); var code = qs.escape(str); console.log(code); console.log(qs.unescape(code));
res:
my@my-THINK MINGW64 /d/workspace/7.11 $ node qs2 aaa%E4%B8%AD%E6%96%87 aaa中文 ---------------------- aaa%E4%B8%AD%E6%96%87 aaa中文
var qs = require("querystring"); //encode|decode //var str = "aaa中文"; var str = "a=12&b=5"; var str = {a:12,b:5}; var code = qs.encode(str);//轉字符串 stringify console.log(code); console.log(qs.decode(code));//轉對象 parse
res:
my@my-THINK MINGW64 /d/workspace/7.11 $ node qs5 a=12&b=5 { a: '12', b: '5' }
url:
url.parse()--->urlObj
url.format(urlObj)--> strUrl
url.resolve(from, to);
URLSearchParams new URLSearchParams();
地址組成: http://www.baidu.com:80/index.html?user=aaa&pass=123#page6 http:// www.baidu.com :80 /index.html ?user=aaa&pass=123 #page6 協議 域名 端口 路徑(資源地址) 數據 錨點 哈希hash location Url { protocol: 'http:', slashes: true, auth: null, host: 'www.baidu.com:80', port: '80', hostname: 'www.baidu.com', hash: '#page6', search: '?user=aaa&pass=123', query: 'user=aaa&pass=123', pathname: '/index.html', path: '/index.html?user=aaa&pass=123', href: 'http://www.baidu.com:80/index.html?user=aaa&pass=123#p age6' } URL { href: 'http://www.baidu.com/index.html?user=aaa&pass=123#page6', origin: 'http://www.baidu.com', protocol: 'http:', username: '', password: '', host: 'www.baidu.com', hostname: 'www.baidu.com', port: '', pathname: '/index.html', search: '?user=aaa&pass=123', searchParams: URLSearchParams { 'user' => 'aaa', 'pass' => '123' }, hash: '#page6' }
var modUrl = require("url"); var url = "http://www.baidu.com:80/index.html?user=aaa&pass=123#page6"; var urlObj = modUrl.parse(url); console.log(1,urlObj); console.log(2,modUrl.format(urlObj));
res:
my@my-THINK MINGW64 /d/workspace/7.11 $ node url1 1 Url { protocol: 'http:', slashes: true, auth: null, host: 'www.baidu.com:80', port: '80', hostname: 'www.baidu.com', hash: '#page6', search: '?user=aaa&pass=123', query: 'user=aaa&pass=123', pathname: '/index.html', path: '/index.html?user=aaa&pass=123', href: 'http://www.baidu.com:80/index.html?user=aaa&pass=123#page6' } 2 'http://www.baidu.com:80/index.html?user=aaa&pass=123#page6'
var modUrl = require("url"); var url = "http://www.baidu.com:9000/index.html?user=aaa&pass=123#page6"; console.log(1,new modUrl.Url(url)); console.log(2,new modUrl.URL(url));
res:
my@my-THINK MINGW64 /d/workspace/7.11 $ node url2 1 Url { protocol: null, slashes: null, auth: null, host: null, port: null, hostname: null, hash: null, search: null, query: null, pathname: null, path: null, href: null } 2 URL { href: 'http://www.baidu.com:9000/index.html?user=aaa&pass=123#page6', origin: 'http://www.baidu.com:9000', protocol: 'http:', username: '', password: '', host: 'www.baidu.com:9000', hostname: 'www.baidu.com', port: '9000', pathname: '/index.html', search: '?user=aaa&pass=123', searchParams: URLSearchParams { 'user' => 'aaa', 'pass' => '123' }, hash: '#page6' }
.resolve(),替換路徑
var modUrl = require("url"); console.log(modUrl.resolve('http://localhost:9000/login', 'index')); console.log(modUrl.resolve('http://localhost:9000/login', '/index')); console.log(modUrl.resolve('http://localhost:9000/users/login', 'index')); //不加/只替換最後一個相對路徑 console.log(modUrl.resolve('http://localhost:9000/users/login', '/index')); //加/替換絕對路徑
res:
my@my-THINK MINGW64 /d/workspace/7.11 $ node url3 http://localhost:9000/index http://localhost:9000/index http://localhost:9000/users/index http://localhost:9000/index
URLSearchParams
new URLSearchParams();
var modUrl = require("url"); var params = new modUrl.URLSearchParams(); console.log(params); params.append("user","aaa"); params.append("pass","123"); //append添加數據 // user=aaa&pass=123 console.log(params); console.log(params.toString());
res:
my@my-THINK MINGW64 /d/workspace/7.11 $ node url4 URLSearchParams {} URLSearchParams { 'user' => 'aaa', 'pass' => '123' } user=aaa&pass=123
//node 10以上,才能夠 var params = new URLSearchParams(); params.append("user","aaa"); params.append("pass","123"); // user=aaa&pass=123 console.log(params.toString());
res:
my@my-THINK MINGW64 /d/workspace/7.11 $ node url5 user=aaa&pass=123
path.parse(path)
path.format(pathObject)
path.basename(path)
path.dirname(path) 路徑
path.extname(path)
path.join() 相對路徑 路徑拼接
path.relative() 獲取的相對路徑 路線圖
path.resolve() 絕對路徑 路徑拼接 碰到絕對路徑 會替換
__dirname 絕對路徑
__filename 絕對地址包含文件名
global 全集對象 至關於 window
var path = require("path"); //win: \ linux / var str = "D:\\wamp64\\www\\20180711\\path.js"; //window要用雙斜線,向右撇 var str = "D:/wamp64/www/20180711/path.js"; var pathObj = path.parse(str); console.log(pathObj);//字符串轉對象 console.log(path.format(pathObj));//對象轉字符串
res:
my@my-THINK MINGW64 /d/workspace/7.11 $ node path1 { root: 'D:/', dir: 'D:/wamp64/www/20180711', base: 'path.js', ext: '.js', name: 'path' } D:/wamp64/www/20180711\path.js
var path = require("path"); var str = "D:/wamp64/www/20180711/path.js"; console.log(path.parse(str)); console.log("--------------------------"); console.log(path.basename(str));//文件名 console.log(path.dirname(str)); //路徑 console.log(path.extname(str));//文件後綴 帶點 console.log("--------------------------"); console.log(__dirname); console.log(__filename);
res:
my@my-THINK MINGW64 /d/workspace/7.11 $ node path2 { root: 'D:/', dir: 'D:/wamp64/www/20180711', base: 'path.js', ext: '.js', name: 'path' } -------------------------- path.js D:/wamp64/www/20180711 .js -------------------------- D:\workspace\7.11 D:\workspace\7.11\path2.js
var path = require("path"); console.log("www"+"/index.html");//只是拼接 console.log(path.join("www","/index.html")); console.log(path.join("www","/////index.html"));//自動去除多餘的/ console.log(path.join("www","index.html"));//自動添加/
res:
my@my-THINK MINGW64 /d/workspace/7.11 $ node path31 www/index.html www\index.html www\index.html www\index.html
var path = require("path"); console.log("www"+"/index.html"); console.log(path.join("\\a","b","c")); console.log(path.join("/a","b","c")); console.log(path.join("a","/b","../c")); //../返回上級目錄
res:
my@my-THINK MINGW64 /d/workspace/7.11 $ node path32 www/index.html \a\b\c \a\b\c a\c
var path = require("path"); console.log(path.relative('/data/orandea/test/aaa', '/data/orandea/impl/bbb')); console.log(path.relative('C:\\orandea\\test\\aaa', 'C:\\orandea\\impl\\bbb'));
res:
my@my-THINK MINGW64 /d/workspace/7.11 $ node path33 ..\..\impl\bbb ..\..\impl\bbb
var path = require("path"); /* resolve返回絕對路徑,參數前不加/, 在後面添加,加/直接替換所有 */ console.log(path.resolve("a","b","c")); console.log(path.resolve("a","/b","/c")); console.log(path.resolve("a/b/c","../d","../e"));
res:
my@my-THINK MINGW64 /d/workspace/7.11 $ node path34 D:\workspace\7.11\a\b\c D:\c D:\workspace\7.11\a\b\e
Buffer 二進制流
操做方式和字符串相似
16進制 0-F
"a".chatCodeAt(0).toString(16); ascii:97 hex:61
97: a (ASCII)
String.fromCharCode(code);//ASCII轉字符
中文的範圍 4e00 - 9fa5
\u4e00(直接轉成中文)
0X4e00(轉成十進制)
hex: 16進制
Buffer.from(...); new Buffer(廢棄)
var str = "abc"; //var buf = new Buffer(str); var buf = Buffer.from(str); console.log(buf); //16進制 中文的範圍 4e00 - 9fa5 console.log("a".charCodeAt(0).toString(16));
res:
$ node buf1 <Buffer 61 62 63> 61
const buf = Buffer.from('abc', 'ascii'); console.log(buf); console.log(buf.toString('hex')); console.log(buf.toString('base64'));
res:
$ node buf2 <Buffer 61 62 63> 616263 YWJj
const buf = Buffer.from([1, 2, 3]); console.log(buf); for(var i = 0; i < buf.length; i++){ console.log(buf[i]); } // Prints: // 1 // 2 // 3 for (const b of buf) { console.log(b); }
res:
$ node buf3 <Buffer 01 02 03> 1 2 3 1 2 3
var buf = Buffer.from([0x61, 0x62, 0x63]); console.log(buf.toString()); var buf = Buffer.from("abc"); console.log(buf.toString());
res:
$ node buf4 abc abc
var buf1 = Buffer.from("abc"); //var buf2 = Buffer.from(buf1); var buf2 = Buffer.from("abc"); console.log(buf1.toString(),buf2.toString());//abc abc console.log(buf1 == buf2);//false console.log(buf1 === buf2);//false console.log(buf1.toString() == buf2.toString());//true console.log(Buffer.compare(buf1, buf2));//0 , 相同爲0,不一樣爲-1
res:
$ node buf42 abc abc false false true 0
var str = "abc中文"; var buf = Buffer.from(str); console.log(buf); console.log(str.length); console.log(buf.length); console.log(Buffer.byteLength(buf));
res:
$ node buf5 <Buffer 61 62 63 e4 b8 ad e6 96 87> 5 9 9
var str = "abc"; var arr = []; for(var i = 0; i < str.length; i++){ arr.push(Buffer.from(str[i]));//61 62 62 arr[buf1,buf2,buf3] } console.log(arr); console.log(Buffer.concat(arr));
res:
$ node buf6 [ <Buffer 61>, <Buffer 62>, <Buffer 63> ] <Buffer 61 62 63>
Buffer.isBuffer() 判斷是不是Buffer
var str = "abc"; console.log(Buffer.isBuffer(str)); var buf = Buffer.from(str); console.log(Buffer.isBuffer(buf));
res:
$ node buf7 false true
.equals()判斷buffer是否相等
const buf1 = Buffer.from('ABC'); const buf2 = Buffer.from('414243', 'hex');//ABC const buf3 = Buffer.from('ABCD'); // 輸出: true console.log(buf1.equals(buf2)); // 輸出: false console.log(buf1.equals(buf3));
res:
$ node buf8 true false
/* buf.includes/indexOf */ var buf = Buffer.from('abcdef'); console.log(buf.includes("def"));//是否包含"def" console.log(buf.indexOf("def")); //是否包含"def",有的話輸出開始下標,沒有的話輸出-1;
res:
$ node buf9 true 3
/* buf.includes/indexOf */ var buf = Buffer.from('abcdef'); console.log(buf.keys()); console.log(buf.values()); //buf是一個對象,需循環輸出key和value console.log("------keys------------"); for(var n of buf.keys()){ console.log(n); } console.log("------values------------"); for(var n of buf.values()){ console.log(n,String.fromCharCode(n)); }
res:
$ node buf10 {} {} ------keys------------ 0 1 2 3 4 5 ------values------------ 97 'a' 98 'b' 99 'c' 100 'd' 101 'e' 102 'f'
var EventEmitter = require("events"); console.log(EventEmitter == EventEmitter.EventEmitter);
res:
$ node evt1 true
var EventEmitter = require("events"); var ev = new EventEmitter(); console.log(ev.on == ev.addListener); //添加事件 //addListener/on ev.on("sum",function(a,b){ console.log("sum:",a+b); }); ev.addListener("abc",function(){ console.log("abc:"); }); //觸發 console.log(1,ev.emit("sum",12,5)); console.log(2,ev.emit("abc"));
res:
$ node evt21 true sum: 17 1 true abc: 2 true
var EventEmitter = require("events"); var ev = new EventEmitter.EventEmitter(); console.log(ev.on == ev.addListener); //添加事件 //addListener/on ev.on("sum",function(a,b){ console.log("sum:",a+b); }); ev.addListener("abc",function(){ console.log("abc:"); }); //觸發 console.log(1,ev.emit("sum",12,5)); console.log(2,ev.emit("abc"));
res:
$ node evt22 true sum: 17 1 true abc: 2 true
var EventEmitter = require("events"); var ev = new EventEmitter(); console.log(1,ev.on == ev.addListener); //添加事件 ev.prependListener("abc",function(){ console.log(2,"abc:"); }); //觸發 console.log(3,ev.emit("abc"));
res:
$ node evt3 1 true 2 'abc:' 3 true
讀寫
fs.readFile 讀
fs.writeFile 寫
fs.appendFile 添加內容
fs.unlink 刪除
fs.copyFile 複製
fs.mkdir 建立
fs.rmdir 刪除
fs.readdir 讀
文件或者目錄是否存在
fs.exists 廢棄
fs.access
判斷是不是文件或者目錄
fs.stat(path,function(stats){ stats.isFile()/isDirectory() })
fs.watch(filename[, options][, listener])
fs.watchFile(filename[, options], listener)
寫比讀先執行
var fs = require("fs"); //readFile/Sync //讀 fs.readFile("a.txt",function(err,data){ console.log(1,err,data); }); //寫,找到a.txt沒有的話建立,添加"aaa"到a.txt fs.writeFile("a.txt","bbb",function(err){ console.log(2,err); //返回null,表示沒有錯誤 });
res:
$ node fs1 2 null 1 null <Buffer 62 62 62>
//copyFile("源文件","目標文件",回調函數)
var fs = require("fs"); //拷貝 一、先讀 二、再寫 //讀 /*fs.readFile("a.txt",function(err,data){ if(err){ console.log("讀取文件失敗"); } else { //寫 fs.writeFile("b.txt",data,function(err){ if(err){ console.log("拷貝失敗"); } else { console.log("拷貝成功"); } }); } }); */ //copyFile("源文件","目標文件",回調函數) fs.copyFile("a.txt","b.txt",function(err){ if(err){ console.log("拷貝失敗"); } else { console.log("拷貝成功"); } });
rse:
$ node fs2 拷貝成功
//appendFile 建立文件或者追加
var fs = require("fs"); //appendFile 建立文件或者追加 fs.appendFile("b.txt","append",function(err){ console.log(err); });
res:
$ node fs3 null
unlink 刪除文件 不能刪除目錄
var fs = require("fs"); //unlink 刪除文件 不能刪除目錄 fs.unlink("b.txt",function(err){ console.log(err); });
res:
$ node fs4 null
//fs.mkdir()建立目錄
var fs = require("fs"); //建立目錄 fs.mkdir("abc", function(err){ console.log(err); });
res:
$ node fs51 null
//刪除目錄fs.rmdir
var fs = require("fs"); //刪除目錄 fs.rmdir("abc", function(err){ console.log(err); });
res:
$ node fs52 null
//讀取目錄fs.readdir
var fs = require("fs"); //讀取目錄 fs.readdir("abc", function(err,res){ console.log(err,res); });
res:
$ node fs53 null [ 'youarebeautiful' ]
fs.exists
//判斷文件和目錄
//文件狀態 文件、目錄是否存在 是文件 仍是目錄
var fs = require("fs"); //判斷文件和目錄 //文件狀態 文件、目錄是否存在 是文件 仍是目錄 fs.exists("abcd", (exists) => { console.log(exists); });
res:
$ node fs61 true
fs.access
var fs = require("fs"); //判斷文件和目錄 //文件狀態 文件、目錄是否存在 是文件 仍是目錄 fs.access("a.txt", (err) => { console.log(err); });
res:
$ node fs62 null
var fs = require("fs"); //判斷文件和目錄 //文件狀態 文件、目錄是否存在 是文件 仍是目錄 fs.stat("abc", (err,stats) => { //stats.isDirectory()是不是目錄/stats.isFile()是不是文件 console.log(err,stats.isFile(),stats.isDirectory()); });
res:
$ node fs63 null false true
var fs = require("fs"); //能夠監聽文件和目錄 //監聽有範圍限制 只有一層 fs.watch("a.txt", (eventType, filename) => { console.log(`事件類型是: ${eventType}-----${filename}`); });
res:
$ node fs71 事件類型是: change-----a.txt 事件類型是: change-----a.txt
var fs = require("fs"); //能夠監聽文件 目錄 有延遲 目錄的文件的修改監聽不到 最好用來監聽文件 fs.watchFile("abc", (curr, prev) => { /*console.log(curr); console.log(prev);*/ console.log(curr.mtime); }); /*Stats { dev: 4145068239, mode: 16822, nlink: 1, uid: 0, gid: 0, rdev: 0, blksize: undefined, ino: 844424930155958, size: 0, blocks: undefined, atimeMs: 1531312004235.5886, mtimeMs: 1531312004235.5886, ctimeMs: 1531312004235.5886, birthtimeMs: 1531311081220.7952, atime: 2018-07-11T12:26:44.236Z, mtime: 2018-07-11T12:26:44.236Z, ctime: 2018-07-11T12:26:44.236Z, birthtime: 2018-07-11T12:11:21.221Z } */
res:
$ node fs72 2018-07-11T12:24:44.050Z
流stream
var rs = fs.createReadStream("src");
var ws = fs.createWriteStream("dist");
rs.pipe(ws);
//一邊讀一邊寫
rs.on("data",function(data){ ws.wrtie(data); }); rs.on("end",function(data){ ws.end(fn); });
res.writeHead(200, { 'content-encoding': 'gzip' });
rs.pipe(zlib.createGzip()).pipe(res);
var fs = require("fs"); //輸入流 輸出 var rs = fs.createReadStream("a.txt"); var ws = fs.createWriteStream("b.txt"); //管道 pipe rs.pipe(ws);將a.txt中的內容一步一步寫入b.txt
res:
$ node stream1
var fs = require("fs"); //輸入流 var rs = fs.createReadStream("a.txt"); rs.on("data",function(data){ console.log(data); }); rs.on("end",function(){ console.log("讀完了"); }); rs.on("error",function(){ console.log("讀取文件失敗"); });
res:
$ node stream2 <Buffer 61 61 61> 讀完了
var fs = require("fs"); var ws = fs.createWriteStream("b.txt"); ws.write("abc",function(){ console.log("write完了"); }); ws.end("end",function(){ console.log("end寫完了"); });
res:
$ node stream3 write完了 end寫完了
var fs = require("fs"); var rs = fs.createReadStream("a.txt"); var ws = fs.createWriteStream("b.txt"); rs.on("data",function(data){ ws.write(data); }); rs.on("end",function(){ console.log("讀完了"); ws.end(function(){ console.log("寫完了"); }); });
res:
$ node stream4 讀完了 寫完了
前面的服務器能夠寫成流 大文件能夠壓縮
var http = require("http"); var fs = require("fs"); var zlib = require("zlib"); var server = http.createServer(function(req,res){ var url = req.url; if(url == "/favicon.ico") return; /*fs.readFile("www"+url,function(err,data){ if(err){ res.end("404"); } else { res.end(data); } });*/ res.writeHead(200, { 'content-encoding': 'gzip' }); var rs = fs.createReadStream("www"+url); rs.pipe(zlib.createGzip()).pipe(res); }); server.listen(9000);
server.js
var http = require("http"); var fs = require("fs"); var zlib = require("zlib"); var modUrl = require("url"); var qs = require("querystring"); var users = {aaa:123}; var server = http.createServer(function(req,res){ var url = req.url; var str = ""; req.on("data",function(data){ str += data; }) req.on("end",function(){ var urlObj = modUrl.parse(url,true); url = urlObj.pathname; var GET = urlObj.query; var POST = qs.parse(str); var params = req.method == "POST" ? POST : GET; var username = params.user; var password = params.pass; if(url == "/login"){ if(users[username]){ if(users[username] == password){ res.end(JSON.stringify({"error":1,"msg":"登錄成功"})); }else{ res.end(JSON.stringify({"error":0,"msg":"用戶名或者密碼錯誤"})); } }else{ res.end(JSON.stringify({"error":0,"msg":"用戶名或者密碼錯誤"})); } }else if(url == "/reg"){ if(users[username]){ res.end(JSON.stringify({"error":0,"msg":"用戶名已存在"})); }else{ users[username] = password; res.end(JSON.stringify({"error":1,"msg":"註冊成功"})); } }else if(url == "/favicon.ico") { return; }else{ res.writeHead(200, { 'content-encoding': 'gzip' }); var rs = fs.createReadStream("www"+url); rs.pipe(zlib.createGzip()).pipe(res); console.log(res); } }) }); server.listen("9000",function(){ console.log("服務器已打開!"); })
user.html
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <script src="jquery.js"></script> <script> $(function(){ $oUser = $("#user"); $oPass = $("#pass"); $oLogin = $("#login"); $oReg = $("#reg"); $oLogin.click(function(){ $.ajax({ type:"get", url:"/login", data:{ user:$oUser.val(), pass:$oPass.val() }, async:true, success:function(str){ alert(str); } }); }); $oReg.click(function(){ $.ajax({ type:"post", url:"/reg", data:{ user:$oUser.val(), pass:$oPass.val() }, async:true, success:function(str){ alert(str); } }); }); }) </script> </head> <body> 用戶名:<input id = "user" type="text" value="aaa"/><br /> 密碼: <input id ="pass" type="text" value="123"/><br /> <input id = "login" type="button" value="登陸"/> <input id = "reg" type="button" value="註冊"/> </body> </html>