一、全局對象(不管是在Node程序中哪一個地方,哪一個時間都可以訪問,主要有一下幾個對象)html
具體用法:前端
// 在這裏能夠經過不一樣運行環境引入不一樣的配置,如端口號、文件編譯壓縮出口等等
let cif = proccess.env.development ? ...require( config.production || config.development ) 複製代碼
process.argv,獲取命令行參數node
//add文件,在這裏,能夠經過輸入命令行,而後加兩個數字作一個簡單的加法
let num1 = parseInt(process.argv[2]);
let num2 = parseInt(process.argv[3]);
let sum = num1 + num2;
setTimeout(()=>{
console.log(sum);
}.1000)
//而後經過運行Node命令行,process.argv=>[node絕對路徑,文件的絕對路徑,參數1,參數2,...]
node ./add.js (文件路徑) 1(第一個參數) 3(第二個參數)
複製代碼
__filename,獲取當前運行文件的絕對路徑react
__dirname,獲取當前運行文件的目錄的絕對路徑jquery
二、核心對象(須要向系統引入,不須要下載)web
path.resolve(__dirname,xxx,xxx),將路徑或路徑片斷的序列解析爲絕對路徑ajax
path.join(__dirname,xxx,xxx),將字符串拼接起來解析成路徑npm
path.join(__dirname), 將路徑解析成一個對象json
三、自定義對象
須要下載,按照路徑引入跨域
// 引入文件
const xxx = require('XXX')
// 導出文件
const xxx = 對象/函數
module.exports xxx複製代碼
const fs = require('fs');
let filepath = 'xxx'; //讀取文件的路徑
// 若是data是
fs.readFile(filepath,'utf-8',(error,data)=>{
if(error)
console.log(error)
// 回調函數返回的是二進制數據Buffer
console.log(data);
// 須要輸出字符串的話,能夠經過toString()轉換
console.log(data.toString())
})複製代碼
2. fs.wirteFile(異步將數據寫入文件,若是文件已存在則覆蓋改文件)
const fs = require('fs')
let filepath = 'xxx' //寫入文件的路徑
// data能夠是一個字符串,也能夠爲buffer,若data爲buffer,encoding(utf-8)則被忽略
fs.writeFile(filepath,data,'utf-8',(error)=>{
if(error){
console.log(error);
}
})複製代碼
3.fs.writeFileSync(同步寫入文件)
fs.writeFileSync(file,data)複製代碼
4.fs.readFileSync (同步讀取文件)
fs.readFileSync(file,data)複製代碼
相關補充點:
fs.access(測試用戶對filepath指定的文件或目錄的權限)
fs.state(獲取文件的狀態)
fs.readdir(讀取文件目錄)
fs.stats類
const fs = require('fs');
const path = require('path); let filepath = 'xxx'; // 判斷文件是否存在 method = fs.constants.F_OK; /* fs.constants.W_OK 文件是否可寫 fs.constants.R_OK 文件是否可 * function findFile(filepath){ try{ fs.access(filepath,method); console.log(${filepath} ${error? '不存在':'存在'}); let state = fs.stateSync(filepath); if(state.isfile()){ console.log(filepath); }else(state.isDireactory()){ let files = fs.readdirSync(filepath); files.forEach(file => { findFile(path.join(filepath,file)); }); }catch(e){ console.log(e); } } 複製代碼
讀寫流——壓縮、加密(fs.createReadStream、fs.createWriteStream、zlib)
const http = require('http');
const fs = require('fs');
const zlib = require('zlib');
http.createServer((req,res)=>{
let filePath = 'xxx'; // 讀取文件的路徑
let rs = fs.createReadStream(filePath); //建立讀取流
rs.on('error',(error)=>{});
res.setHeadr('content-encoding','gzip'); //發送響應頭,告知瀏覽器返回的數據格式
let gz = zlip.createGzip(); // 壓縮
rs.pipe(gz).pipe(res); // pipe管道,將上一步的結果做爲輸入,而後進行相應的處理
}).listen(8080);複製代碼
// 建立一個server服務
const http = require('http');
let server = http.createServer((req,res)=>{
// req 是瀏覽器請求的內容,有關請求的內容均可以從req裏面獲取
// res 是服務器返回的響應
res.write();
res.end();
})
server.listen(8080);複製代碼
const http = require('http');
const url = require('url');
http.createServer((req,res)=>{
console.log(req.url); // 輸出例子: /aaa?user=test&password=123,/aaa爲地址,後面爲數據
let {pathname,query} = url.parse(req.url,true);
console.log(pathname); // 輸出 /aaa
console.log(query); //輸出 {username: 'test', password: '123'},將GET請求方式的數據解析成一個對象
}).listen(8080);複製代碼
const http=require('http');
const querystring=require('querystring');
let server=http.createServer(function (req, res){
let url = req.url;
console.log(req.url); // /aaa,由於是POST方式,因此地址不帶有數據
let arr=[];
// 這裏接收的data爲十六進制數據
req.on('data', buffer=>{
arr.push(buffer);
});
req.on('end', ()=>{
let buffer=Buffer.concat(arr);
console.log(buffer.toString()); // user=test&password=123
let post=querystring.parse(buffer.toString());
console.log(post); // {user: 'test',password: '123} }); }); server.listen(8080);複製代碼
querystring.parse(),將user=test&password=123這類數據格式轉換成一個json對象
quertstring.stringify(),將json對象轉換成user=test&password=123數據格式
(須要將HTML中form表單提交方式爲POST,enctype="multipart/formdata")
使用前先下載
npm i multiparty複製代碼
const http=require('http');
const multiparty=require('multiparty');
http.createServer((req, res)=>{
let form=new multiparty.Form({
uploadDir: './upload' //文件上傳的路徑
});
form.parse(req);
// 解析普通form表單數據
form.on('field', (name, value)=>{
console.log('字段:', name, value); //user 123
});
// 解析上傳文件的信息
form.on('file', (name, file)=>{
console.log('文件:', name, file);
});
form.on('close', ()=>{
console.log('表單解析完成');
});
}).listen(8080);複製代碼
返回請求頭
const http = require('http');
http.createServer((req,res)=>{
res.setHeader('Content-Type','text/html');
res.setHeader('x-Foo','bar');
res.writeHead(200, {'Content-Type': 'text/plain'});
// res.writeHead(200,{'Content-Type': 'text/html;charset=utf-8'});
// res.writeHead(200,{'Content-Type': 'application/json'});
res.end();
}).listen(8080);複製代碼
獲取請求頭
const http = require('http');
http.createServer((req,res)=>{
let header = req.headers; // 獲取請求頭
let url = req.url; // 獲取域名
let method = req.method; //獲取請求方式
}).listen(8080);複製代碼
原生ajax跨域問題,由於SOP(同源策略機制),ajax向服務器發出請求時(不是直接向服務器發出請求),首先是向瀏覽器發起請求,而後瀏覽器再向服務器發出請求,服務器返回請求結果,而後瀏覽器接收到請求結果,判斷請求的結果與ajax是否處於同一域名下,若是不是,則丟棄,反之,則將結果返回給ajax。要想原生ajax能成功跨域,則須要服務器作出聲明。
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<script>
window.onload=function (){
let oBtn=document.getElementById('btn1');
oBtn.onclick=function (){
let ajax=new XMLHttpRequest();
ajax.open('GET', 'http://localhost:8080/a', true);
ajax.send();
ajax.onreadystatechange=function (){
if(ajax.readyState==4){
if(ajax.status==200){
alert('成功');
let json=JSON.parse(ajax.responseText);
console.log(json);
}else{
alert('失敗');
}
}
};
};
};
</script>
</head>
<body>
<input type="button" value="請求" id="btn1">
</body>
</html>複製代碼
const http = require('http');
http.createServer((req,res)=>{
let allOrigin = {
'http://localhost': 'true',
'http://xxx.xxx': 'true',
'http://xxx/xxx': 'true'
}
// 獲取域名
let { origin } = req.headers;
// 發送聲明
if(allOrigin[origin]){
res.setHeader('access-control-allow-origin','*');
}
}).listen(8080);複製代碼
(原生,能夠解析普通文本、JSON、二進制數據)
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<script>
window.onload=function (){
let oBtn=document.getElementById('btn1');
let img1=document.getElementById('img1');
// fetch是異步請求的方式,這裏利用了ES6的async/await語法
oBtn.onclick=async function (){
//1.請求
// let res=await fetch('data/1.txt'); //普通文本數據
// let res = await fetch('data/1.json'); //json數據
let res = await fetch('data/1.png'); // 二進制數據
//2.解析數據,也是異步方式
// let str= await res.text();
// alert(str);
// let json = await res.json();
// console.log(json);
let data = await res.blod(); //解析二進制數據
let url = URL.createObjectURL(data); //在本地臨時建立保存一個url
img1.src = url;
};
};
</script>
</head>
<body>
<input type="button" value="讀取" id="btn1">
<img id="img1" />
</body>
</html>複製代碼
FormDate(前端處理表單數據,而後交給ajax提交數據)、Ajax、multiparty(Node)配合使用
原生Ajax提交數據
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<form id="form1" action="http://localhost:8080/" method="post">
用戶:<input type="text" name="user" /><br>
密碼:<input type="password" name="pass" /><br>
文件:<input type="file" name="f1" /><br>
<input type="submit" value="提交">
</form>
</body>
<script>
let oForm=document.querySelector('#form1');
oForm.onsubmit=function (){
let formdata=new FormData(oForm);
let xhr=new XMLHttpRequest();
xhr.open(oForm.method, oForm.action, true);
xhr.send(formdata);
xhr.onreadystatechange=function (){
if(xhr.readyState==4){
if(xhr.status==200){
alert('成功');
}else{
alert('失敗');
}
}
};
return false;
};
</script>
</html>複製代碼
const http=require('http');
const multiparty=require('multiparty');
http.createServer((req, res)=>{
let form=new multiparty.Form({
uploadDir: './upload' //文件上傳的路徑
});
form.parse(req);
// 解析普通form表單數據
form.on('field', (name, value)=>{
console.log('字段:', name, value); //user 123
});
// 解析上傳文件的信息
form.on('file', (name, file)=>{
console.log('文件:', name, file);
});
form.on('close', ()=>{
console.log('表單解析完成');
});
}).listen(8080);複製代碼
JQuery-Ajax
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<form id="form1" action="http://localhost:8080/" method="post">
用戶:<input type="text" name="user" /><br>
密碼:<input type="password" name="pass" /><br>
文件:<input type="file" name="f1" /><br>
<input type="submit" value="提交">
</form>
</body>
<script src="jquery.js" charset="utf-8"></script>
<script>
$('#form1').on('submit', function (){
let formdata=new FormData(this);
$.ajax({
url: this.action,
type: this.method,
data: formdata,
/* JQuery會自動將data中上傳的數據轉換成另一種格式,因此會致使數據格式不正確,致使失敗 */
processData: false, // 不須要轉換數據格式
/* JQuery會自動提交一個contentType,致使失敗 */
contentType: false // 不須要篡改contentType
}).then(res=>{
alert('成功');
}, res=>{
alert('失敗');
});
return false;
});
</script>
</html>複製代碼
若無form表單,可自定義一個FormData(Ajax2.0),而後在FormData裏添加內容
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div id="div1">
用戶:<input type="text" id="user" /><br>
密碼:<input type="password" id="pass" /><br>
文件:<input type="file" id="f1" /><br>
<input id="btn1" type="button" value="提交">
</div>
</body>
<script>
let oBtn=document.querySelector('#btn1');
oBtn.onclick=function (){
let formdata=new FormData();
formdata.append('username', document.querySelector('#user').value);
formdata.append('password', document.querySelector('#pass').value);
formdata.append('f1', document.querySelector('#f1').files[0]);
//
let xhr=new XMLHttpRequest();
xhr.open('post', 'http://localhost:8080/', true);
xhr.send(formdata);
xhr.onreadystatechange=function (){
if(xhr.readyState==4){
if(xhr.status==200){
alert('成功');
}else{
alert('失敗');
}
}
};
};
</script>
</html>複製代碼
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<script>
// 建立scoket
let ws=new WebSocket('ws://localhost:8080/');
// 創建鏈接
ws.onopen=function (){
alert('鏈接已創建');
};
// 數據交互
ws.onmessage=function (){};
// 鏈接關閉
ws.onclose=function (){};
// 鏈接發送錯誤
ws.onerror=function (){};
</script>
</head>
<body>
</body>
</html>
複製代碼
const net=require('net');
const crypto=require('crypto');
// 解析瀏覽器請求頭(字符串),解析成JSON對象
function parseHeader(str){
let arr=str.split('\r\n').filter(line=>line);
arr.shift();
let headers={};
arr.forEach(line=>{
let [name, value]=line.split(':');
name=name.replace(/^\s+|\s+$/g, '').toLowerCase();
value=value.replace(/^\s+|\s+$/g, '');
headers[name]=value;
});
return headers;
}
// 建立服務器
let server=net.createServer(sock=>{
sock.once('data', buffer=>{
// 首次接收請求頭可轉換成字符串
let str=buffer.toString();
let headers=parseHeader(str);
// 判斷瀏覽器發來的請求頭中協議是否升級爲websocket
if(headers['upgrade']!='websocket'){
console.log('no upgrade');
sock.end();
}else if(headers['sec-websocket-version']!='13'){ //判斷websocket版本
console.log('no 13');
sock.end();
}else{
// 獲取key
let key=headers['sec-websocket-key'];
// websocket固定的驗證方式
let uuid='258EAFA5-E914-47DA-95CA-C5AB0DC85B11';
let hash=crypto.createHash('sha1');
hash.update(key+uuid);
let key2=hash.digest('base64');
// 發送返回頭報文
sock.write(`HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection:upgrade\r\nSec-Websocket-Accept:${key2}\r\n\r\n`);
}
});
sock.on('end', ()=>{
});
});
server.listen(8080);複製代碼
(簡單方便,自動解析,兼容IE5,自帶跨域)
前端用法:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
// 服務器自動返回socket.io
<script src="http://localhost:8080/socket.io/socket.io.js" charset="utf-8"></script>
<script>
// 鏈接scoket.io
let sock=io.connect('ws://localhost:8080/');
// 發送數據 sock.emit(函數名字,數據值1,數據值2)
//sock.emit('aaa', 12, 5);
// 接收數據 sock.in(函數名字,(參數1,參數2)=>{})
sock.on('timer', time=>{
console.log(time);
});
</script>
</head>
<body>
</body>
</html>複製代碼
服務器:
npm i socket.io複製代碼
const http=require('http');
const io=require('socket.io');
//1.創建普通http
let server=http.createServer((req, res)=>{});
server.listen(8080);
//2.創建ws
let wsServer=io.listen(server);
wsServer.on('connection', sock=>{
//sock.emit('name', 數據)
//sock.on('name', function (數據){});
/*sock.on('aaa', function (a, b){
console.log(a, b, a+b);
});*/
setInterval(function (){
sock.emit('timer', new Date().getTime());
}, 1000);
});
複製代碼