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 @ 73ff653a

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_cares: 'false',
303
         node_shared_http_parser: 'false',
304
         node_shared_v8: 'false',
305
         node_shared_zlib: 'false',
306
         node_use_dtrace: 'false',
307
         node_use_openssl: 'true',
308
         node_shared_openssl: 'false',
309
         strict_aliasing: 'true',
310
         target_arch: 'x64',
311
         v8_use_snapshot: 'true' } }
312

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

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

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

    
324
Example of sending a signal to yourself:
325

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

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

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

    
337

    
338
## process.pid
339

    
340
The PID of the process.
341

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

    
344
## process.title
345

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

    
348

    
349
## process.arch
350

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

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

    
355

    
356
## process.platform
357

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

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

    
363

    
364
## process.memoryUsage()
365

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

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

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

    
373
This will generate:
374

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

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

    
381

    
382
## process.nextTick(callback)
383

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

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

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

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

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

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

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

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

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

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

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

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

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

    
432
This approach is much better:
433

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

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

    
443
## process.maxTickDepth
444

    
445
* {Number} Default = 1000
446

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

    
452
Consider this code:
453

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

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

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

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

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

    
472
    var oldmask, newmask = 0644;
473

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

    
478

    
479
## process.uptime()
480

    
481
Number of seconds Node has been running.
482

    
483

    
484
## process.hrtime()
485

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

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

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

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

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

    
506
[EventEmitter]: events.html#events_class_events_eventemitter