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 @ bfd78b69

History | View | Annotate | Download (13 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_http_parser: 'false',
303
         node_shared_v8: 'false',
304
         node_shared_zlib: 'false',
305
         node_use_dtrace: 'false',
306
         node_use_openssl: 'true',
307
         node_shared_openssl: 'false',
308
         strict_aliasing: 'true',
309
         target_arch: 'x64',
310
         v8_use_snapshot: 'true' } }
311

    
312
## process.kill(pid, [signal])
313

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

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

    
323
Example of sending a signal to yourself:
324

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

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

    
334
    process.kill(process.pid, 'SIGHUP');
335

    
336

    
337
## process.pid
338

    
339
The PID of the process.
340

    
341
    console.log('This process is pid ' + process.pid);
342

    
343
## process.title
344

    
345
Getter/setter to set what is displayed in 'ps'.
346

    
347

    
348
## process.arch
349

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

    
352
    console.log('This processor architecture is ' + process.arch);
353

    
354

    
355
## process.platform
356

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

    
360
    console.log('This platform is ' + process.platform);
361

    
362

    
363
## process.memoryUsage()
364

    
365
Returns an object describing the memory usage of the Node process
366
measured in bytes.
367

    
368
    var util = require('util');
369

    
370
    console.log(util.inspect(process.memoryUsage()));
371

    
372
This will generate:
373

    
374
    { rss: 4935680,
375
      heapTotal: 1826816,
376
      heapUsed: 650472 }
377

    
378
`heapTotal` and `heapUsed` refer to V8's memory usage.
379

    
380

    
381
## process.nextTick(callback)
382

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

    
388
    process.nextTick(function() {
389
      console.log('nextTick callback');
390
    });
391

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

    
396
    function MyThing(options) {
397
      this.setupOptions(options);
398

    
399
      process.nextTick(function() {
400
        this.startDoingStuff();
401
      }.bind(this));
402
    }
403

    
404
    var thing = new MyThing();
405
    thing.getReadyForStuff();
406

    
407
    // thing.startDoingStuff() gets called now, not before.
408

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

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

    
419
      fs.stat('file', cb);
420
    }
421

    
422
This API is hazardous.  If you do this:
423

    
424
    maybeSync(true, function() {
425
      foo();
426
    });
427
    bar();
428

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

    
431
This approach is much better:
432

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

    
439
      fs.stat('file', cb);
440
    }
441

    
442
## process.maxTickDepth
443

    
444
* {Number} Default = 1000
445

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

    
451
Consider this code:
452

    
453
    process.nextTick(function foo() {
454
      process.nextTick(foo);
455
    });
456

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

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

    
465
## process.umask([mask])
466

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

    
471
    var oldmask, newmask = 0644;
472

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

    
477

    
478
## process.uptime()
479

    
480
Number of seconds Node has been running.
481

    
482

    
483
## process.hrtime()
484

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

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

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

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

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

    
505
[EventEmitter]: events.html#events_class_events_eventemitter