(function(exports, require, module, __filename, __dirname) {
// 模塊的代碼實際上在這裏
});
複製代碼
exportsnode
exports = global.exports = {} (注意這是個對象,實際對外導出的是global.exports)chrome
module數組
module = global.module = {} (注意這是個對象,實際對外導出的是global.module)bash
require()函數
引包ui
__filename編碼
當前模塊的文件名稱---解析後的絕對路徑。 在主程序中這不必定要跟命令行中使用的名稱一致。spa
__dirname操作系統
當前模塊的文件夾名稱。等同於 __filename 的 path.dirname() 的值。命令行
經常使用屬性
Events:uncaughtException
process.on('uncaughtException', (err) => {
fs.writeSync(1, `Caught exception: ${err}\n`);
});
setTimeout(() => {
console.log('This will still run.');
}, 500);
// 故意調用一個不存在的函數,應用會拋出未捕獲的異常
nonexistentFunc();
console.log('This will not run.');
複製代碼
argv
屬性返回一個數組,這個數組包含了啓動Node.js進程時的命令行參數。第一個元素爲process.execPath。若是須要獲取argv[0]的值請參見 process.argv0。第二個元素爲當前執行的JavaScript文件路徑。剩餘的元素爲其餘命令行參數
```
例如,process-args.js文件有如下代碼:
// print process.argv
process.argv.forEach((val, index) => {
console.log(`${index}: ${val}`);
});
運行如下命令,啓動進程:
$ node process-args.js one two=three four
將輸出:
0: /usr/local/bin/node
1: /Users/mjr/work/node/process-args.js
2: one
3: two=three
4: four
```
複製代碼
```
例如:
$ node --harmony script.js --version
process.execArgv的結果:
['--harmony']
process.argv的結果:
['/usr/local/bin/node', 'script.js', '--version']
```
複製代碼
一個包含用戶環境信息的對象
方法返回 Node.js 進程當前工做的目錄
inspect
// chrome打開 chrome://inspect/#devices
$ node --inspect process-args.js
// 進入程序開始時打斷點
$ node --inspect-brk process-args.js
複製代碼
process.nextTick 插入到當前隊列隊尾,setImmediate 插入到下個隊列隊首
例如:
setImmediate(() => console.log('setImmediate'))
setTimeout(() => console.log('setTimeout'), 0)
process.nextTick(() => console.log('nextTick'))
輸出:
nextTick
setTimeout
setImmediate
複製代碼
格式化路徑
拼接路徑,內部會調用normalize
獲取一個目標文件的絕對路徑
獲取文件名(路徑),不一樣操做系統獲取的不同
獲取所在文件夾路徑
獲取文件的拓展名
解析一個路徑,並返回一個包含這個路徑信息的對象
把parse()返回的對象從新組合成字符串並返回這個字符串
// 建立一個長度爲 十、且用 0 填充的 Buffer。
const buf1 = Buffer.alloc(10);
// 建立一個長度爲 十、且用 0x1 填充的 Buffer。
const buf2 = Buffer.alloc(10, 1);
複製代碼
// 建立一個長度爲 十、且未初始化的 Buffer。
// 這個方法比調用 Buffer.alloc() 更快,
// 但返回的 Buffer 實例可能包含舊數據,
// 所以須要使用 fill() 或 write() 重寫。
const buf3 = Buffer.allocUnsafe(10);
複製代碼
// 建立一個包含 [0x1, 0x2, 0x3] 的 Buffer。
const buf4 = Buffer.from([1, 2, 3]);
// 建立一個包含 UTF-8 字節 [0x74, 0xc3, 0xa9, 0x73, 0x74] 的 Buffer。
const buf5 = Buffer.from('tést');
// 建立一個包含 Latin-1 字節 [0x74, 0xe9, 0x73, 0x74] 的 Buffer。
const buf6 = Buffer.from('tést', 'latin1');
複製代碼
// 字符串的編碼長度
Buffer.byteLength('test')
複製代碼
isBuffer()
concat(list[, totalLength])
5
// 例子
const EventEmitter = require('events');
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
myEmitter.on('event', () => {
console.log('觸發了一個事件!');
});
myEmitter.emit('event');
複製代碼