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

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

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

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

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

    
322
Example of sending a signal to yourself:
323

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

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

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

    
335

    
336
## process.pid
337

    
338
The PID of the process.
339

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

    
342
## process.title
343

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

    
346

    
347
## process.arch
348

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

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

    
353

    
354
## process.platform
355

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

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

    
361

    
362
## process.memoryUsage()
363

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

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

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

    
371
This will generate:
372

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

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

    
379

    
380
## process.nextTick(callback)
381

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

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

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

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

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

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

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

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

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

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

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

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

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

    
430
This approach is much better:
431

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

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

    
441
## process.maxTickDepth
442

    
443
* {Number} Default = 1000
444

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

    
450
Consider this code:
451

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

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

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

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

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

    
470
    var oldmask, newmask = 0644;
471

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

    
476

    
477
## process.uptime()
478

    
479
Number of seconds Node has been running.
480

    
481

    
482
## process.hrtime()
483

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

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

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

    
495
    setTimeout(function() {
496
      t = process.hrtime(t);
497
      // [ 1, 6962306 ]
498

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

    
503
[EventEmitter]: events.html#events_class_events_eventemitter