
nodejs常用知識(shí)點(diǎn)
nodejs中require方法的過程
// Check the cache for the requested file.
// 1. If a module already exists in the cache: return its exports object.
// 2. If the module is native: call `NativeModule.require()` with the filename and return the result.
// 3. Otherwise, create a new module for the file and save it to the cache.Then have it load the file contents before returning its exports object.
在module.js中會(huì)先調(diào)用_load方法,當(dāng)該模塊既不在cache中,也不是nativeModule,需要?jiǎng)?chuàng)建Module的實(shí)例(調(diào)用_compile方法),并加入緩存中,同時(shí)返回exports方法。
而在es6中引入了Module,提供了require方法,那么它和commonJs的require方法有什么區(qū)別呢?
- 非運(yùn)行時(shí)
可以做靜態(tài)代碼分析,在運(yùn)行前分析模塊之間的依賴關(guān)系,運(yùn)行代碼檢查。 - 更好支持依賴循環(huán)
在Nodejs中如果模塊之間存在相互引用,可能會(huì)引發(fā)意想不到的結(jié)果。而在es6中,是不會(huì)關(guān)心是否發(fā)生了"循環(huán)加載",生成的是指向被加載模塊的引用。
什么是error-first回調(diào)模式?
應(yīng)用error-first回調(diào)模式是為了更好的進(jìn)行錯(cuò)誤和數(shù)據(jù)的傳遞。第一個(gè)參數(shù)保留給一個(gè)錯(cuò)誤error對(duì)象,一旦出錯(cuò),錯(cuò)誤將通過第一個(gè)參數(shù)error返回。其余的參數(shù)將用作數(shù)據(jù)的傳遞。
fs.readFile(filePath, function(err, data) {
if (err) {
// handle the error, the return is important here
// so execution stops here
return console.log(err)
}
// use the data object
console.log(data)
})
require方法加載順序源碼
當(dāng) Node 遇到 require(X) 時(shí),會(huì)依次按下面的順序處理。
- 如果 X 是內(nèi)置模塊(比如 require('http'))
- 返回該模塊。
- 不再繼續(xù)執(zhí)行。
- 如果 X 以 "./" 或者 "/" 或者 "../" 開頭
- 根據(jù) X 所在的父模塊,確定 X 的絕對(duì)路徑。
- 將 X 當(dāng)成文件,依次查找下面文件,只要其中有一個(gè)存在,就返回該文件,不再繼續(xù)執(zhí)行。
X
X.js
X.json
X.node
3. 將 X 當(dāng)成目錄,依次查找下面文件,只要其中有一個(gè)存在,就返回該文件,不再繼續(xù)執(zhí)行。
X/package.json
X/index.js
X/index.json
X/index.node
- 如果 X 不帶路徑
- 根據(jù) X 所在的父模塊,確定 X 可能的安裝目錄。
- 依次在每個(gè)目錄中,將 X 當(dāng)成文件名或目錄名加載。
- 拋出 "not found"
process.nextTick
先通過一段代碼看看process.nextTick干了什么
function foo() {
console.error('foo');
}
process.nextTick(foo);
console.error('bar');
-------------
bar
foo
通過上述代碼,可以看到程序先輸出Bar,再輸出foo。在js中我們可以通過setTimeout(function(){},0)來實(shí)現(xiàn)這個(gè)功能。
但是在內(nèi)部處理機(jī)制上,process.nextTick和setTimeout(fn,0)是有明顯區(qū)別的。
process.nextTick時(shí)間復(fù)雜度o(1),而setTimeout(fn,0)的時(shí)間復(fù)雜度o(log(n))[紅黑樹]。
process.nextTick中傳入的函數(shù),都是在當(dāng)前執(zhí)行棧的尾部觸發(fā)。最大嵌套層級(jí)是1000。
注:
nextTick傳入的callback執(zhí)行先于任何IO事件。(It runs before any additional I/O events (including timers) fire in subsequent ticks of the event loop..)
nodejs處理cpu密集型
let http = require('http');
let server = http.createServer((req,res)=>{
let url = req.url;
if(url.indexOf('test')>=0){
while(1){
console.log('a');
}
}else{
console.log('b');
}
});
server.listen(3000,()=>{
console.log("監(jiān)聽3000端口");
});
運(yùn)行上述代碼,控制臺(tái)無法輸出b;
mysql包
pool.query方法是流程pool.getConnection -> connection.query -> connection.release的縮寫
該npm包默認(rèn)使用sqlstring包對(duì)sql語句進(jìn)行生成