NodeJS常用內(nèi)置模塊
Process
表示當(dāng)前進(jìn)程低飒,常用的屬性和方法
-
process.env
環(huán)境變量 -
process.version
當(dāng)前node.js版本 -
process.versions
依賴庫的版本號 -
process.platform
運(yùn)行平臺 -
process.arch
CPU架構(gòu) -
process.cwd()
许昨,當(dāng)前工作目錄
// console.log(process)
// console.log('環(huán)境變量信息', process.env)
console.log('當(dāng)前node版本信息',process.version)
console.log('依賴庫的版本號',process.versions)
console.log('運(yùn)行平臺',process.platform)
console.log('CPU架構(gòu)', process.arch)
console.log('當(dāng)前工作目錄', process.cwd())
-
Node也是事件驅(qū)動的單線程模型,可以通過nextTick nextTick方法用于將一個函數(shù)推遲到代碼中所書寫的下一個同步方法執(zhí)行完畢或異步方法的回調(diào)函數(shù)開始執(zhí)行前調(diào)用褥赊。
console.log(1); setTimeout(() => { console.log(5) }) process.nextTick(() => { console.log(3); }); process.nextTick(() => { console.log(4); }); setTimeout(() => { console.log(6) }) console.log(2); // 執(zhí)行結(jié)果是 1 2 3 4 5 6 //先執(zhí)行同步事件糕档,然后執(zhí)行nextTick中的回調(diào),最后才會執(zhí)行定時器中的回調(diào)
使用process不需要引入
fs 文件讀寫
fs模塊提供了異步與同步的讀寫文件功能拌喉。
異步就是指 執(zhí)行I/O操作時速那,不需要等待,在回調(diào)函數(shù)中進(jìn)行操作尿背,繼續(xù)執(zhí)行后續(xù)代碼端仰。
同步就是指 當(dāng)遇到I/O操作時,會等到操作完成后田藐, 才繼續(xù)往后執(zhí)行代碼荔烧。
使用fs模塊,需要先引入 const fs = require('fs')
1汽久、異步讀取文件
fs.readFile(path [, options], callback)
- path 第一個參數(shù)指定讀取的文件
- opations 第二個參數(shù)可選鹤竭,指定文件的編碼
- callback 第三個參數(shù)指定回調(diào),回調(diào)中接收兩個參數(shù)景醇,第一個參數(shù)是發(fā)生錯誤時候的錯誤對象臀稚,如果不發(fā)生錯誤,那么對應(yīng)的值為null三痰, 第二個參數(shù)是讀取到的文件內(nèi)容吧寺。
當(dāng)不傳入第二個參數(shù),指定文件的編碼時散劫,返回的是Buffer
對象(一個包含0或多個字節(jié)的數(shù)組稚机,但和Array不同)
- 可以把Buffer對象轉(zhuǎn)為string
buffer.toString('utf-8')
- 也可以把字符串轉(zhuǎn)成Buffer對象
new Buffer(text, 'utf-8')
// 引入fs模塊
const fs = require('fs')
// 未指定編碼格式
fs.readFile('./index.js', (err, data) => {
console.log('err',err)
console.log('data',data)
console.log('data', data.toString())
})
// 指定編碼格式
fs.readFile('./index.js', 'utf-8',(err, data) => {
console.log('err',err)
console.log('data',data)
})
2、異步寫文件
fs.writeFile(path, data[,options] callback)
- Path 文件路徑获搏。 如果指定的文件不存在赖条,會自動創(chuàng)建一個文件,并將內(nèi)容寫入
- data 要寫入的內(nèi)容颜凯, 如果傳入的data是String谋币,那么默認(rèn)以UTF-8編碼寫入文件,如果傳入的是
Buffer
對象症概,那么以二進(jìn)制形式寫入文件 - Callback 文件寫入完成之后執(zhí)行的回調(diào)函數(shù)蕾额,有一個參數(shù)是發(fā)生錯誤時的錯誤對象,如果不發(fā)生錯誤彼城,那么對應(yīng)的值為null
// 引入fs模塊
const fs = require('fs')
fs.writeFile('./index1.js', 'Hello World','utf-8', (err) => {
console.log(err)
})
3诅蝶、同步讀取文件
fs.readFileSync(path[, options])
同步讀寫不接受回調(diào)函數(shù)退个,如果需要處理異常,可以使用try/catch
實現(xiàn)效果
// 引入fs模塊
const fs = require('fs')
try {
fs.readFileSync('./index.js','utf-8')
}
catch(err) {
console.log(err)
}
4调炬、同步寫文件
fs.writeFileSync(path, data[, fileEncoding])
多次寫入文件语盈, 最后一次操作會覆蓋之前寫入的內(nèi)容。
// 引入fs模塊
const fs = require('fs')
fs.writeFileSync('./index.js', 'test', 'utf-8')
fs.writeFileSync('./index.js', 'test1', 'utf-8')
fs.writeFileSync('./index.js', 'test2', 'utf-8')
5缰泡、同異步追加內(nèi)容
fs.appendFile
和fs.appendFileSync
可以向文件中追加內(nèi)容
path 路徑
1刀荒、path.basename(path[, ext])
獲取一個路徑中的文件名
2、path.dirname(path[, ext])
獲取一個路徑中的目錄文件夾名
3棘钞、path.extname
獲取一個路徑中的文件擴(kuò)展名
const path = require('path')
console.log("basename",path.basename('./test/index.js')) // index.js
console.log("dirname",path.dirname('./test/index.js')) // ./test
console.log("extname",path.extname('./test/index.js')) // .js
4缠借、path.resolve()
根據(jù)當(dāng)前文件所在目錄,解析出絕對路徑
可以傳遞多個參數(shù)宜猜,從后向前進(jìn)行拼接泼返。
若字符以 / 開頭,不會拼接到前面的路徑(
因為拼接到此已經(jīng)是一個絕對路徑
)姨拥;若以 ../ 開頭绅喉,拼接前面的路徑,且不含最后一節(jié)路徑叫乌;
若以 ./ 開頭 或者沒有符號 則拼接前面路徑柴罐;
var path = require("path") //引入node的path模塊
path.resolve('/foo/bar', './baz') // returns '/foo/bar/baz'
path.resolve('/foo/bar', 'baz') // returns '/foo/bar/baz'
path.resolve('/foo/bar', '/baz') // returns '/baz'
path.resolve('/foo/bar', '../baz') // returns '/foo/baz'
path.resolve('home','/foo/bar', '../baz') // returns '/foo/baz'
path.resolve('home','./foo/bar', '../baz') // returns '/home/foo/baz'
path.resolve('home','foo/bar', '../baz') // returns '/home/foo/baz'
如果在處理完所有給定的 path 片段之后還未生成絕對路徑,則再加上當(dāng)前工作目錄
http 模塊
Nodejs提供了request
和response
對象综芥,用來處理數(shù)據(jù)請求和響應(yīng)
-
request
對象封裝了http請求 -
response
對象封裝了http響應(yīng)
1丽蝎、引入http模塊
2猎拨、創(chuàng)建http服務(wù)器
3膀藐、監(jiān)聽端口號
4、啟動本地服務(wù)器 node xx.js
5红省、瀏覽器訪問 localhost:port
const http = require('http')
const server = http.createServer((request, response) => {
response.writeHead(200, {'Content-Type': 'text/html'});
response.end("This is a server by Node.js");
});
server.listen('3000',() => {
console.log('3000 port is linsening')
})
url 模塊
url一般是結(jié)合http模塊一起使用额各, 對請求地址進(jìn)行處理
-
url.parse(req.url)
把一個完整的url
地址分解為一個對象
const http = require('http')
const url = require('url')
const server = http.createServer((req, res) => {
// 由于在通過chrome瀏覽器的方式在進(jìn)行訪問時,每次訪問都會默認(rèn)附帶一次/favicon.ico的請求吧恃、可以添加判斷
if(req.url == '/favicon.ico'){
return;
};
console.log('req.url', req.url)
// url.parse解析
let urlParse = url.parse(req.url)
console.log('urlParse',urlParse )
res.writeHead(200, {'Content-Type': 'text/html'});
res.end("This is a server by Node.js");
});
server.listen('3000',() => {
console.log('3000 port is linsening')
})
-
Url.parse有兩個常用屬性
-
Pathname
獲取文件路徑的字符串虾啦,以/開頭,不包括參數(shù) -
query
獲取參數(shù)痕寓,如果在轉(zhuǎn)化是傲醉,parse方法的第二個參數(shù)傳遞為true,自動將傳遞的參數(shù)轉(zhuǎn)變?yōu)閷ο蟾袷?/li>
-