The data contained in this repository can be downloaded to your computer using one of several clients.
Please see the documentation of your version control software client for more information.

Please select the desired protocol below to get the URL.

This URL has Read-Only access.

Statistics
| Branch: | Revision:

main_repo / doc / api / process.markdown @ 38809e39

History | View | Annotate | Download (13.1 KB)

1
# process
2

    
3
<!-- type=global -->
4

    
5
The `process` object is a global object and can be accessed from anywhere.
6
It is an instance of [EventEmitter][].
7

    
8

    
9
## Event: 'exit'
10

    
11
Emitted when the process is about to exit.  This is a good hook to perform
12
constant time checks of the module's state (like for unit tests).  The main
13
event loop will no longer be run after the 'exit' callback finishes, so
14
timers may not be scheduled.
15

    
16
Example of listening for `exit`:
17

    
18
    process.on('exit', function() {
19
      setTimeout(function() {
20
        console.log('This will not run');
21
      }, 0);
22
      console.log('About to exit.');
23
    });
24

    
25
## Event: 'uncaughtException'
26

    
27
Emitted when an exception bubbles all the way back to the event loop. If a
28
listener is added for this exception, the default action (which is to print
29
a stack trace and exit) will not occur.
30

    
31
Example of listening for `uncaughtException`:
32

    
33
    process.on('uncaughtException', function(err) {
34
      console.log('Caught exception: ' + err);
35
    });
36

    
37
    setTimeout(function() {
38
      console.log('This will still run.');
39
    }, 500);
40

    
41
    // Intentionally cause an exception, but don't catch it.
42
    nonexistentFunc();
43
    console.log('This will not run.');
44

    
45
Note that `uncaughtException` is a very crude mechanism for exception
46
handling and may be removed in the future.
47

    
48
Don't use it, use [domains](domain.html) instead. If you do use it, restart
49
your application after every unhandled exception!
50

    
51
Do *not* use it as the node.js equivalent of `On Error Resume Next`. An
52
unhandled exception means your application - and by extension node.js itself -
53
is in an undefined state. Blindly resuming means *anything* could happen.
54

    
55
Think of resuming as pulling the power cord when you are upgrading your system.
56
Nine out of ten times nothing happens - but the 10th time, your system is bust.
57

    
58
You have been warned.
59

    
60
## Signal Events
61

    
62
<!--type=event-->
63
<!--name=SIGINT, SIGUSR1, etc.-->
64

    
65
Emitted when the processes receives a signal. See sigaction(2) for a list of
66
standard POSIX signal names such as SIGINT, SIGUSR1, etc.
67

    
68
Example of listening for `SIGINT`:
69

    
70
    // Start reading from stdin so we don't exit.
71
    process.stdin.resume();
72

    
73
    process.on('SIGINT', function() {
74
      console.log('Got SIGINT.  Press Control-D to exit.');
75
    });
76

    
77
An easy way to send the `SIGINT` signal is with `Control-C` in most terminal
78
programs.
79

    
80

    
81
## process.stdout
82

    
83
A `Writable Stream` to `stdout`.
84

    
85
Example: the definition of `console.log`
86

    
87
    console.log = function(d) {
88
      process.stdout.write(d + '\n');
89
    };
90

    
91
`process.stderr` and `process.stdout` are unlike other streams in Node in
92
that writes to them are usually blocking.  They are blocking in the case
93
that they refer to regular files or TTY file descriptors. In the case they
94
refer to pipes, they are non-blocking like other streams.
95

    
96

    
97
## process.stderr
98

    
99
A writable stream to stderr.
100

    
101
`process.stderr` and `process.stdout` are unlike other streams in Node in
102
that writes to them are usually blocking.  They are blocking in the case
103
that they refer to regular files or TTY file descriptors. In the case they
104
refer to pipes, they are non-blocking like other streams.
105

    
106

    
107
## process.stdin
108

    
109
A `Readable Stream` for stdin. The stdin stream is paused by default, so one
110
must call `process.stdin.resume()` to read from it.
111

    
112
Example of opening standard input and listening for both events:
113

    
114
    process.stdin.resume();
115
    process.stdin.setEncoding('utf8');
116

    
117
    process.stdin.on('data', function(chunk) {
118
      process.stdout.write('data: ' + chunk);
119
    });
120

    
121
    process.stdin.on('end', function() {
122
      process.stdout.write('end');
123
    });
124

    
125

    
126
## process.argv
127

    
128
An array containing the command line arguments.  The first element will be
129
'node', the second element will be the name of the JavaScript file.  The
130
next elements will be any additional command line arguments.
131

    
132
    // print process.argv
133
    process.argv.forEach(function(val, index, array) {
134
      console.log(index + ': ' + val);
135
    });
136

    
137
This will generate:
138

    
139
    $ node process-2.js one two=three four
140
    0: node
141
    1: /Users/mjr/work/node/process-2.js
142
    2: one
143
    3: two=three
144
    4: four
145

    
146

    
147
## process.execPath
148

    
149
This is the absolute pathname of the executable that started the process.
150

    
151
Example:
152

    
153
    /usr/local/bin/node
154

    
155

    
156
## process.abort()
157

    
158
This causes node to emit an abort. This will cause node to exit and
159
generate a core file.
160

    
161
## process.chdir(directory)
162

    
163
Changes the current working directory of the process or throws an exception if that fails.
164

    
165
    console.log('Starting directory: ' + process.cwd());
166
    try {
167
      process.chdir('/tmp');
168
      console.log('New directory: ' + process.cwd());
169
    }
170
    catch (err) {
171
      console.log('chdir: ' + err);
172
    }
173

    
174

    
175

    
176
## process.cwd()
177

    
178
Returns the current working directory of the process.
179

    
180
    console.log('Current directory: ' + process.cwd());
181

    
182

    
183
## process.env
184

    
185
An object containing the user environment. See environ(7).
186

    
187

    
188
## process.exit([code])
189

    
190
Ends the process with the specified `code`.  If omitted, exit uses the
191
'success' code `0`.
192

    
193
To exit with a 'failure' code:
194

    
195
    process.exit(1);
196

    
197
The shell that executed node should see the exit code as 1.
198

    
199

    
200
## process.getgid()
201

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

    
204
Gets the group identity of the process. (See getgid(2).)
205
This is the numerical group id, not the group name.
206

    
207
    if (process.getgid) {
208
      console.log('Current gid: ' + process.getgid());
209
    }
210

    
211

    
212
## process.setgid(id)
213

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

    
216
Sets the group identity of the process. (See setgid(2).)  This accepts either
217
a numerical ID or a groupname string. If a groupname is specified, this method
218
blocks while resolving it to a numerical ID.
219

    
220
    if (process.getgid && process.setgid) {
221
      console.log('Current gid: ' + process.getgid());
222
      try {
223
        process.setgid(501);
224
        console.log('New gid: ' + process.getgid());
225
      }
226
      catch (err) {
227
        console.log('Failed to set gid: ' + err);
228
      }
229
    }
230

    
231

    
232
## process.getuid()
233

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

    
236
Gets the user identity of the process. (See getuid(2).)
237
This is the numerical userid, not the username.
238

    
239
    if (process.getuid) {
240
      console.log('Current uid: ' + process.getuid());
241
    }
242

    
243

    
244
## process.setuid(id)
245

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

    
248
Sets the user identity of the process. (See setuid(2).)  This accepts either
249
a numerical ID or a username string.  If a username is specified, this method
250
blocks while resolving it to a numerical ID.
251

    
252
    if (process.getuid && process.setuid) {
253
      console.log('Current uid: ' + process.getuid());
254
      try {
255
        process.setuid(501);
256
        console.log('New uid: ' + process.getuid());
257
      }
258
      catch (err) {
259
        console.log('Failed to set uid: ' + err);
260
      }
261
    }
262

    
263

    
264
## process.version
265

    
266
A compiled-in property that exposes `NODE_VERSION`.
267

    
268
    console.log('Version: ' + process.version);
269

    
270
## process.versions
271

    
272
A property exposing version strings of node and its dependencies.
273

    
274
    console.log(process.versions);
275

    
276
Will output:
277

    
278
    { node: '0.4.12',
279
      v8: '3.1.8.26',
280
      ares: '1.7.4',
281
      ev: '4.4',
282
      openssl: '1.0.0e-fips' }
283

    
284
## process.config
285

    
286
An Object containing the JavaScript representation of the configure options
287
that were used to compile the current node executable. This is the same as
288
the "config.gypi" file that was produced when running the `./configure` script.
289

    
290
An example of the possible output looks like:
291

    
292
    { target_defaults:
293
       { cflags: [],
294
         default_configuration: 'Release',
295
         defines: [],
296
         include_dirs: [],
297
         libraries: [] },
298
      variables:
299
       { host_arch: 'x64',
300
         node_install_npm: 'true',
301
         node_prefix: '',
302
         node_shared_cares: 'false',
303
         node_shared_http_parser: 'false',
304
         node_shared_libuv: 'false',
305
         node_shared_v8: 'false',
306
         node_shared_zlib: 'false',
307
         node_use_dtrace: 'false',
308
         node_use_openssl: 'true',
309
         node_shared_openssl: 'false',
310
         strict_aliasing: 'true',
311
         target_arch: 'x64',
312
         v8_use_snapshot: 'true' } }
313

    
314
## process.kill(pid, [signal])
315

    
316
Send a signal to a process. `pid` is the process id and `signal` is the
317
string describing the signal to send.  Signal names are strings like
318
'SIGINT' or 'SIGUSR1'.  If omitted, the signal will be 'SIGTERM'.
319
See kill(2) for more information.
320

    
321
Note that just because the name of this function is `process.kill`, it is
322
really just a signal sender, like the `kill` system call.  The signal sent
323
may do something other than kill the target process.
324

    
325
Example of sending a signal to yourself:
326

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

    
331
    setTimeout(function() {
332
      console.log('Exiting.');
333
      process.exit(0);
334
    }, 100);
335

    
336
    process.kill(process.pid, 'SIGHUP');
337

    
338

    
339
## process.pid
340

    
341
The PID of the process.
342

    
343
    console.log('This process is pid ' + process.pid);
344

    
345
## process.title
346

    
347
Getter/setter to set what is displayed in 'ps'.
348

    
349

    
350
## process.arch
351

    
352
What processor architecture you're running on: `'arm'`, `'ia32'`, or `'x64'`.
353

    
354
    console.log('This processor architecture is ' + process.arch);
355

    
356

    
357
## process.platform
358

    
359
What platform you're running on:
360
`'darwin'`, `'freebsd'`, `'linux'`, `'sunos'` or `'win32'`
361

    
362
    console.log('This platform is ' + process.platform);
363

    
364

    
365
## process.memoryUsage()
366

    
367
Returns an object describing the memory usage of the Node process
368
measured in bytes.
369

    
370
    var util = require('util');
371

    
372
    console.log(util.inspect(process.memoryUsage()));
373

    
374
This will generate:
375

    
376
    { rss: 4935680,
377
      heapTotal: 1826816,
378
      heapUsed: 650472 }
379

    
380
`heapTotal` and `heapUsed` refer to V8's memory usage.
381

    
382

    
383
## process.nextTick(callback)
384

    
385
On the next loop around the event loop call this callback.
386
This is *not* a simple alias to `setTimeout(fn, 0)`, it's much more
387
efficient.  It typically runs before any other I/O events fire, but there
388
are some exceptions.  See `process.maxTickDepth` below.
389

    
390
    process.nextTick(function() {
391
      console.log('nextTick callback');
392
    });
393

    
394
This is important in developing APIs where you want to give the user the
395
chance to assign event handlers after an object has been constructed,
396
but before any I/O has occurred.
397

    
398
    function MyThing(options) {
399
      this.setupOptions(options);
400

    
401
      process.nextTick(function() {
402
        this.startDoingStuff();
403
      }.bind(this));
404
    }
405

    
406
    var thing = new MyThing();
407
    thing.getReadyForStuff();
408

    
409
    // thing.startDoingStuff() gets called now, not before.
410

    
411
It is very important for APIs to be either 100% synchronous or 100%
412
asynchronous.  Consider this example:
413

    
414
    // WARNING!  DO NOT USE!  BAD UNSAFE HAZARD!
415
    function maybeSync(arg, cb) {
416
      if (arg) {
417
        cb();
418
        return;
419
      }
420

    
421
      fs.stat('file', cb);
422
    }
423

    
424
This API is hazardous.  If you do this:
425

    
426
    maybeSync(true, function() {
427
      foo();
428
    });
429
    bar();
430

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

    
433
This approach is much better:
434

    
435
    function definitelyAsync(arg, cb) {
436
      if (arg) {
437
        process.nextTick(cb);
438
        return;
439
      }
440

    
441
      fs.stat('file', cb);
442
    }
443

    
444
## process.maxTickDepth
445

    
446
* {Number} Default = 1000
447

    
448
Callbacks passed to `process.nextTick` will *usually* be called at the
449
end of the current flow of execution, and are thus approximately as fast
450
as calling a function synchronously.  Left unchecked, this would starve
451
the event loop, preventing any I/O from occurring.
452

    
453
Consider this code:
454

    
455
    process.nextTick(function foo() {
456
      process.nextTick(foo);
457
    });
458

    
459
In order to avoid the situation where Node is blocked by an infinite
460
loop of recursive series of nextTick calls, it defers to allow some I/O
461
to be done every so often.
462

    
463
The `process.maxTickDepth` value is the maximum depth of
464
nextTick-calling nextTick-callbacks that will be evaluated before
465
allowing other forms of I/O to occur.
466

    
467
## process.umask([mask])
468

    
469
Sets or reads the process's file mode creation mask. Child processes inherit
470
the mask from the parent process. Returns the old mask if `mask` argument is
471
given, otherwise returns the current mask.
472

    
473
    var oldmask, newmask = 0644;
474

    
475
    oldmask = process.umask(newmask);
476
    console.log('Changed umask from: ' + oldmask.toString(8) +
477
                ' to ' + newmask.toString(8));
478

    
479

    
480
## process.uptime()
481

    
482
Number of seconds Node has been running.
483

    
484

    
485
## process.hrtime()
486

    
487
Returns the current high-resolution real time in a `[seconds, nanoseconds]`
488
tuple Array. It is relative to an arbitrary time in the past. It is not
489
related to the time of day and therefore not subject to clock drift. The
490
primary use is for measuring performance between intervals.
491

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

    
495
    var time = process.hrtime();
496
    // [ 1800216, 927643717 ]
497

    
498
    setTimeout(function() {
499
      var diff = process.hrtime(time);
500
      // [ 1, 6962306 ]
501

    
502
      console.log('benchmark took %d seconds and %d nanoseconds',
503
                  diff[0], diff[1]);
504
      // benchmark took 1 seconds and 6962306 nanoseconds
505
    }, 1000);
506

    
507
[EventEmitter]: events.html#events_class_events_eventemitter