Node.js 的Process全局对象

 Process

           The process object is a global object and can be accessed from anywhere.It is an instance of EventEmitter.

           Process对象是glogal的一个属性,可以在任何地方访问,它也是事件发射的一个实例。

序号名称描述
1Event: 'exit'Process退出是注册的事件。
process.on('exit', function(code) {
  // do *NOT* do this
  setTimeout(function() {
    console.log('This will not run');
  }, 0);
  console.log('About to exit with code:', code);
});
2Event: 'uncaughtException'没有捕获的异常注册的事件。
process.on('uncaughtException', function(err) {
  console.log('Caught exception: ' + err);
});
请注意,uncaughtException是异常处理一个很粗的机制和可能在将来被移除。
不要使用它,使用domain的实例。如使用它,每个没有处理的异常会重启运用。

3Signal EventsProcess接收到一个信号注册的事件。
// Start reading from stdin so we don't exit.
process.stdin.resume();

process.on('SIGINT', function() {
  console.log('Got SIGINT.  Press Control-D to exit.');
});
4process.stdout在标准输出设备输出流,console.log定义
console.log = function(d) {
  process.stdout.write(d + '\n');
};
5process.stderr 
6process.stdin接收一个输入流
process.stdin.setEncoding('utf8');

process.stdin.on('readable', function() {
  var chunk = process.stdin.read();
  if (chunk !== null) {
    process.stdout.write('data: ' + chunk);
  }
});

process.stdin.on('end', function() {
  process.stdout.write('end');
});
7process.argv命令行的参数数组。
$ node argv.js 1991 name=byvoid --v "Carbo Kuo"
参数为:第一个:node
                第二个:argv.js
                第三个:1991
                第四个:name=byvoid --v
                第五个:"Carbo Kuo"
8process.execPathprocess启动的路径.
9process.execArgvprocess执行的参数。
$ node --harmony script.js --version
process.execArgv为:['--harmony']
process.argv为['/usr/local/bin/node', 'script.js', '--version']
10process.abort()退出
11process.chdir(directory)改变当前路径到directory指定的路径。
12process.cwd()返回当前路径。
13process.env用户环境对象。
14process.exit([code])code 指定的值结束process,code为0,标示正常结束(success),其它非正常结束(failure)。
process.exit(1);
15process.getgid()Gets the group identity of the process.This is the numerical group id, not the group name.
Note: this function is only available on POSIX platforms (i.e. not Windows)
if (process.getgid) {
  console.log('Current gid: ' + process.getgid());
}
16process.setgid(id)Sets the group identity of the process. (See setgid(2).) This accepts eithera numerical ID or a groupname string. If a groupname is specified, this methodblocks while resolving it to a numerical ID.
Note: this function is only available on POSIX platforms (i.e. not Windows)
if (process.getgid && process.setgid) {
  console.log('Current gid: ' + process.getgid());
  try {
    process.setgid(501);
    console.log('New gid: ' + process.getgid());
  }
  catch (err) {
    console.log('Failed to set gid: ' + err);
  }
}
17process.getuid()Gets the user identity of the process. (See getuid(2).)This is the numerical userid, not the username.
Note: this function is only available on POSIX platforms (i.e. not Windows)
if (process.getuid) {
  console.log('Current uid: ' + process.getuid());
}
18process.setuid(id)Note: this function is only available on POSIX platforms (i.e. not Windows)
if (process.getuid && process.setuid) {
  console.log('Current uid: ' + process.getuid());
  try {
    process.setuid(501);
    console.log('New uid: ' + process.getuid());
  }
  catch (err) {
    console.log('Failed to set uid: ' + err);
  }
}
19process.getgroups()

Note: this function is only available on POSIX platforms (i.e. not Windows)

Returns an array with the supplementary group IDs. POSIX leaves it unspecifiedif the effective group ID is included but node.js ensures it always is.

20process.setgroups(groups)

Note: this function is only available on POSIX platforms (i.e. not Windows)

Sets the supplementary group IDs. This is a privileged operation, meaning youneed to be root or have the CAP_SETGID capability.

The list can contain group IDs, group names or both.

21process.initgroups(user, extra_group)

Note: this function is only available on POSIX platforms (i.e. not Windows)

Reads /etc/group and initializes the group access list, using all groups ofwhich the user is a member. This is a privileged operation, meaning you needto be root or have the CAP_SETGID capability.

user is a user name or user ID. extra_group is a group name or group ID.

Some care needs to be taken when dropping privileges. Example:

console.log(process.getgroups());         // [ 0 ]
process.initgroups('bnoordhuis', 1000);   // switch user
console.log(process.getgroups());         // [ 27, 30, 46, 1000, 0 ]
process.setgid(1000);                     // drop root gid
console.log(process.getgroups());         // [ 27, 30, 46, 1000 ]
22process.versionA compiled-in property that exposes NODE_VERSION.
console.log('Version: ' + process.version);
23process.versionsA property exposing version strings of node and its dependencies.
console.log(process.versions);
24process.configAn Object containing the JavaScript representation of the configure optionsthat were used to compile the current node executable. This is the same asthe "config.gypi" file that was produced when running the ./configure script.
25process.kill(pid, [signal])发送一个信号给process.

process.on('SIGHUP', function() {
  console.log('Got SIGHUP signal.');
});

setTimeout(function() {
  console.log('Exiting.');
  process.exit(0);
}, 100);

process.kill(process.pid, 'SIGHUP');
26process.pidThe PID of the process.
console.log('This process is pid ' + process.pid);
27process.titleGetter/setter to set what is displayed in 'ps'.
28process.archWhat processor architecture you're running on: 'arm', 'ia32', or 'x64'.
console.log('This processor architecture is ' + process.arch);
29process.platformWhat platform you're running on:'darwin', 'freebsd', 'linux', 'sunos' or 'win32'
console.log('This platform is ' + process.platform);
30process.memoryUsage()Returns an object describing the memory usage of the Node processmeasured in bytes.
var util = require('util');

console.log(util.inspect(process.memoryUsage()));
This will generate:
{ rss: 4935680,
  heapTotal: 1826816,
  heapUsed: 650472 }

31process.nextTick(callback)On the next loop around the event loop call this callback.This is not a simple alias to setTimeout(fn, 0), it's much moreefficient. It typically runs before any other I/O events fire, but thereare some exceptions. See process.maxTickDepth below.
process.nextTick(function() {
  console.log('nextTick callback');
});
This is important in developing APIs where you want to give the user thechance to assign event handlers after an object has been constructed,but before any I/O has occurred.
function MyThing(options) {
  this.setupOptions(options);

  process.nextTick(function() {
    this.startDoingStuff();
  }.bind(this));
}

var thing = new MyThing();
thing.getReadyForStuff();

// thing.startDoingStuff() gets called now, not before.
It is very important for APIs to be either 100% synchronous or 100%asynchronous. Consider this example:
// WARNING!  DO NOT USE!  BAD UNSAFE HAZARD!
function maybeSync(arg, cb) {
  if (arg) {
    cb();
    return;
  }

  fs.stat('file', cb);
}
This API is hazardous. If you do this:
maybeSync(true, function() {
  foo();
});
bar();

then it's not clear whether foo() or bar() will be called first.

This approach is much better:

function definitelyAsync(arg, cb) {
  if (arg) {
    process.nextTick(cb);
    return;
  }

  fs.stat('file', cb);
}
32process.maxTickDepth 
33process.umask([mask]) 
34process.uptime()Number of seconds Node has been running.
35process.hrtime()

Returns the current high-resolution real time in a [seconds, nanoseconds]tuple Array. It is relative to an arbitrary time in the past. It is notrelated to the time of day and therefore not subject to clock drift. Theprimary use is for measuring performance between intervals.

You may pass in the result of a previous call to process.hrtime() to geta diff reading, useful for benchmarks and measuring intervals:

var time = process.hrtime();
// [ 1800216, 25 ]

setTimeout(function() {
  var diff = process.hrtime(time);
  // [ 1, 552 ]

  console.log('benchmark took %d nanoseconds', diff[0] * 1e9 + diff[1]);
  // benchmark took 1000000527 nanoseconds
}, 1000);
36  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值