nodejs常用知識點(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中會先調(diào)用_load方法
筛峭,當(dāng)該模塊既不在cache中,也不是nativeModule,需要創(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中如果模塊之間存在相互引用,可能會引發(fā)意想不到的結(jié)果唬涧。而在es6中今艺,是不會關(guān)心是否發(fā)生了"循環(huán)加載",生成的是指向被加載模塊的引用爵卒。
什么是error-first回調(diào)模式虚缎?
應(yīng)用error-first回調(diào)模式是為了更好的進(jìn)行錯誤和數(shù)據(jù)的傳遞。第一個(gè)參數(shù)保留給一個(gè)錯誤error對象,一旦出錯实牡,錯誤將通過第一個(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í)创坞,會依次按下面的順序處理碗短。
- 如果 X 是內(nèi)置模塊(比如 require('http'))
- 返回該模塊。
- 不再繼續(xù)執(zhí)行题涨。
- 如果 X 以 "./" 或者 "/" 或者 "../" 開頭
- 根據(jù) X 所在的父模塊偎谁,確定 X 的絕對路徑。
- 將 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ā)窖梁。最大嵌套層級是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)行上述代碼纵刘,控制臺無法輸出b
;
mysql包
pool.query
方法是流程pool.getConnection -> connection.query -> connection.release
的縮寫
該npm包默認(rèn)使用sqlstring
包對sql語句進(jìn)行生成