1 process.on('exit', function(code) { 2 // do *NOT* do this 3 setTimeout(function() { 4 console.log('This will not run'); 5 }, 0); 6 console.log('About to exit with code: ', code); 7 });
1 process.on('uncaughtException', function(err) { 2 console.log('Caught exception: ' + err); 3 }); 4 5 setTimeout(function() { 6 console.log('This will still run.'); 7 }, 500); 8 9 // Intentionally cause an exception, but don't catch it 10 nonexitstentFunc(); 11 console.log('This will not run.');
注意 uncaughtException 是一種很是粗魯的異常捕獲途徑且有可能在未來移除。
不要使用它,使用 domains 取代。若是你使用了它,在每一個沒被正常捕獲的異常後重啓你的應用程序。
不要使用它由於 node.js 至關於出了錯待會恢復從新開始。一個未捕獲的異常意味着你的應用程序——推而廣之 node.js 自己處於未知狀態。盲目地恢復意味着什麼事情都有可發生。
假想當你正在升級系統時拔了電源線,而後恢復了。十次有九次都沒事發生——但在第十次,你的系統就崩了。
你已經被警告過。node
1 // Start reading from stdin so we don't exit. 2 process.stdin.resume(); 3 4 process.on('SIGINT', function() { 5 console.log('Got SIGINT. Press Control-D to exit.'); 6 });
在大多數的終端程序中一個簡單的發送 SIGINT 信號的方法是使用 Control-C。
注意:linux
注意 Windows 不支持發送信號,但 node 使用 process.kill() 和 child_process.kill() 提供了一些模擬:——發送信號0能夠用來查找進程是否存在——發送 SIGINT,SIGTERM 和 SIGKILL 讓目標進程無條件退出。shell
1 console.log = function(d) { 2 process.stdout.write(d + '\n'); 3 };
process.stderr 和 process.stdout 和 Node 中的其餘流不一樣,向它們寫入一般是阻塞的。npm
$ node -p "Boolean(process.stdin.isTTY)" true $ echo "foo" | node -p "Boolean(process.stdin.isTTY)" false $ node -p "Boolean(process.stdout.isTTY)" true $ node -p "Boolean(process.stdout.isTTY)" | cat false
更多信息參看 tty 文檔。api
1 process.stdin.setEncoding('utf8'); 2 3 process.stdin.on('readable', function() { 4 var chunk = process.stdin.read(); 5 if (chunk !== null) { 6 process.stdout.write('data ' + chunk); 7 } 8 }); 9 10 process.stdin.on('end', function() { 11 process.stdout.write('end'); 12 });
做爲一個流,process.stdin 也能夠用於「老」模式,那是爲了兼容使用 v0.10 以前的 node 所寫的代碼。更多信息參看流兼容性。
在「老」模式下標準輸入流默認是暫停的,因此必須調用 process.stdin.resume() 來從從裏面讀取。並且須要注意調用 process.stdin.resume() 自己會將流選擇爲「老」模式。
若是你正在啓動一個新項目,你應該選擇更現代的「新」流模式而不是「老」的。數組
1 // print process.argv 2 process.argv.forEach(function(val, index, array) { 3 console.log(index + ': ' + val); 4 });
輸出將會是:安全
$ node process-2.js one two=three four 0: node 1: /User/mjr/work/node/process-2.js 2: one 3: two=three 4: four
/usr/local/bin/node
$ node --harmony script.js --version
process.execArgv 的結果:架構
['--harmony']
process.argv 的結果:
dom
['/usr/local/bin/node', 'script.js', '--version']
這會致使 node 發射一個 abort。這回引發 node 退出並建立一個核心文件。異步
1 console.log('Starting directory: ' + process.cwd()); 2 try { 3 process.chdir('/tmp'); 4 console.log('New directory: ' + process.cwd()); 5 } 6 catch (err) { 7 console.log('chdir: ' + err); 8 }
1 console.log('Current directory: ' + process.cwd());
1 process.exit(1);
執行 node 的 shell 將看到1做爲退出碼。
1 if (process.gid) { 2 console.log('Current gid: ' + process.getgid()); 3 }
1 if (process.getgid && process.setgid) { 2 console.log('Current gid: ' + process.getgid()); 3 try { 4 process.setgid(501); 5 console.log('New gid: ' + process.getgid()); 6 } 7 catch (err) { 8 console.log('Failed to set gid: ' + err); 9 } 10 }
1 if (process.getuid) { 2 console.log('Current uid: ' + process.getuid()); 3 }
1 if (process.getuid && porcess.setuid) { 2 console.log('Current uid: ' + process.getuid()); 3 try { 4 process.setuid(501); 5 console.log('New uid: ' + process.getuid()); 6 } 7 catch (err) { 8 console.log('Failed to set uid: ' + err); 9 } 10 }
1 console.log(process.getgroups()); // [ 0 ] 2 process.initgroups('bnoordhuis', 1000); // switch user 3 console.log(process.getgroups()); // [ 27, 30, 46, 1000, 0 ] 4 process.setgid(1000); // drop root gid 5 console.log(process.getgroups()); // [ 27, 30, 40, 1000 ]
1 console.log('Version: ' + process.version);
1 console.log(process.versions);
將打印以下輸出:
{ http_parser: '1.0', node: '0.10.4', v8: '3.14.5.8', ares: '1.9.0-DEV', uv: '0.10.3', zlib: '1.2.3', modules: '11', openssl: '1.0.1e' }
{ target_defaults: { cflags: [], default_configuration: 'Release', defines: [], include_dirs: [], libraries: [] }, variables: { host_arch: 'x64', node_install_npm: 'true', node_prefix: '', node_shared_cares: 'false', node_shared_http_parser: 'false', node_shared_libuv: 'false', node_shared_v8: 'false', node_shared_zlib: 'false', node_use_dtrace: 'false', node_use_openssl: 'true', node_shared_openssl: 'false', strict_aliasing: 'true', target_arch: 'x64', v8_use_snapshot: 'true' } }
1 process.on('SIGHUP', function() { 2 console.log('Got SIGHUP signal.'); 3 }); 4 5 setTimeout(function() { 6 console.log('Existing.'); 7 process.exit(0); 8 }, 100); 9 10 process.kill(process.pid, 'SIGHUP');
注意:當 Node.js 接收到 SIGUSR1 它會啓動調試器,參看 Signal Events。
1 console.log('This process is pid ' + process.pid);
1 console.log('This processor architecture is ' + process.arch);
1 console.log('This platform is ' + process.platform);
1 var util = require('util'); 2 3 console.log(util.inspect(process.memoryUsage()));
這將打印:
{ rss: 4935680, heapTotal: 1826816, heapUsed: 650472 }
heapTotal 和 heapUsed 表示 V8 的內存使用。
1 process.nextTick(function() { 2 console.log('nextTick callback'); 3 });
在開發 API 時若你想給用戶機會去在對象被建立以後但在任何 I/O 發生以前分配事件監聽器,這個函數是很重要的。
1 function MyThing(options) { 2 this.setupOptions(options); 3 4 process.nextTick(function() { 5 this.startDoingStuff(); 6 }.bind(this)); 7 } 8 9 var thing = new MyThing(); 10 thing.getReadyForStuff(); 11 12 // thing.startDoingStuff() gets called now, not before.
保證 API 是100%同步的或100%異步的是很是重要的。考慮下面的例子:
1 // WARNING! DO NOT USE! BAD UNSAFE HAZARD! 2 function maybeSync(arg, cb) { 3 if (arg) { 4 cb(); 5 return; 6 } 7 8 fs.stat('file', cb); 9 }
這個 API 是冒險的。若是你執行下面:
1 maybeSync(true, function() { 2 foo(); 3 }); 4 bar();
那麼不清楚到底 foo() 仍是 bar() 先被執行。
這個方法會更好:
1 function definitelyAsync(arg, cb) { 2 if (arg) { 3 process.nextTick(cb); 4 return; 5 } 6 7 fs.stat('file', cb); 8 }
1 process.nextTick(function foo() { 2 process.nextTick(foo); 3 });
爲了不 Node 被一系列遞歸 nextTick 無限循環鎖阻塞,它會延遲來讓一些 I/O 每隔一段時間被執行。
process.maxTickDepth 的值是 nextTick 調用 nextTick 回調函數的最大深度,以在容許其餘形式的 I/O 發起前進行評估。
1 var oldmask, newmask = 0644; 2 3 oldmask = process.umask(newmask); 4 console.log('Changed umask from: ' + oldmask.toString(8) + 5 ' to ' + newmask.tostring(8));
1 var time = process.hrtime(); 2 // [ 1800216, 25 ] 3 4 setTimeout(function() { 5 var diff = process.hrtime(time); 6 // [ 1, 552] 7 8 console.log('benchmark took %d nanoseconds', diff[0] * 1e9 + diff[1]); 9 // benchmark took 1000000527 nanaseconds 10 }, 1000);