• No se han encontrado resultados

Preservación de documentos (agrupada)

When set to 1 colors will not be used in the REPL.

NODE_ICU_DATA=file#

Data path for ICU (Intl object) data. Will extend linked-in data when compiled with small-icu support.

NODE_REPL_HISTORY=file#

Path to the file used to store the persistent REPL history. The default path is ~/.node_repl_history, which is overridden by this variable. Setting the value to an empty string ("" or " ") disables persistent REPL history.

 Console

 Asynchronous vs Synchronous Consoles

 Class: Console

 new Console(stdout[, stderr])

 console.assert(value[, message][, ...])

 console.dir(obj[, options])

 console.error([data][, ...])

 console.info([data][, ...])

 console.log([data][, ...])

 console.time(label)

 console.timeEnd(label)

 console.trace(message[, ...])

 console.warn([data][, ...]) Console#

Stability: 2 - Stable

The console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.

The module exports two specific components:

 A Console class with methods such

as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.

 A global console instance configured to write to stdout and stderr.

Because this object is global, it can be used without callingrequire('console').

Example using the global console:

console.log('hello world');

// Prints: hello world, to stdout console.log('hello %s', 'world');

// Prints: hello world, to stdout

console.error(new Error('Whoops, something bad happened'));

// Prints: [Error: Whoops, something bad happened], to stderr const name = 'Will Robinson';

console.warn(`Danger ${name}! Danger!`);

// Prints: Danger Will Robinson! Danger!, to stderr Example using the Console class:

const out = getStreamSomehow();

const err = getStreamSomehow();

const myConsole = new console.Console(out, err);

myConsole.log('hello world');

// Prints: hello world, to out

myConsole.log('hello %s', 'world');

// Prints: hello world, to out

myConsole.error(new Error('Whoops, something bad happened'));

// Prints: [Error: Whoops, something bad happened], to err const name = 'Will Robinson';

myConsole.warn(`Danger ${name}! Danger!`);

// Prints: Danger Will Robinson! Danger!, to err

While the API for the Console class is designed fundamentally around the browser console object, the Console in Node.js is not intended to duplicate the browser's functionality exactly.

Asynchronous vs Synchronous Consoles#

The console functions are asynchronous unless the destination is a file.

Disks are fast and operating systems normally employ write-back caching;

it should be a very rare occurrence indeed that a write blocks, but it is possible.

Class: Console#

The Console class can be used to create a simple logger with configurable output streams and can be accessed using

either require('console').Consoleor console.Console:

const Console = require('console').Console;

const Console = console.Console;

new Console(stdout[, stderr])#

Creates a new Console by passing one or two writable stream

instances. stdout is a writable stream to print log or info output. stderr is used for warning or error output. If stderr isn't passed, warning and error output will be sent to stdout.

const output = fs.createWriteStream('./stdout.log');

const errorOutput = fs.createWriteStream('./stderr.log');

// custom simple logger

const logger = new Console(output, errorOutput);

// use it like console var count = 5;

logger.log('count: %d', count);

// in stdout.log: count 5

The global console is a special Console whose output is sent to process.stdout and process.stderr. It is equivalent to calling:

new Console(process.stdout, process.stderr);

console.assert(value[, message][, ...])#

A simple assertion test that verifies whether value is truthy. If it is not, an AssertionError is thrown. If provided, the error message is formatted usingutil.format() and used as the error message.

console.assert(true, 'does nothing');

// OK

console.assert(false, 'Whoops %s', 'didn\'t work');

// AssertionError: Whoops didn't work

Note: the console.assert() method is implemented differently in Node.js than the console.assert() method available in browsers.

Specifically, in browsers, calling console.assert() with a falsy assertion will cause the message to be printed to the console without interrupting

execution of subsequent code. In Node.js, however, a falsy assertion will cause an AssertionError to be thrown.

Functionality approximating that implemented by browsers can be implemented by extending Node.js' console and overriding

the console.assert()method.

In the following example, a simple module is created that extends and overrides the default behavior of console in Node.js.

'use strict';

// Creates a simple extension of console with a // new impl for assert without monkey-patching.

const myConsole = Object.setPrototypeOf({

assert(assertion, message, ...args) { try {

console.assert(assertion, message, ...args);

} catch (err) {

console.error(err.stack);

} }

}, console);

module.exports = myConsole;

This can then be used as a direct replacement for the built in console:

const console = require('./myConsole');

console.assert(false, 'this message will print, but no error thrown');

console.log('this will also print');

console.dir(obj[, options])#

Uses util.inspect() on obj and prints the resulting string to stdout. This function bypasses any custom inspect() function defined on obj. An optional options object may be passed to alter certain aspects of the formatted string:

showHidden - if true then the object's non-enumerable and symbol properties will be shown too. Defaults to false.

depth - tells util.inspect() how many times to recurse while

formatting the object. This is useful for inspecting large complicated objects. Defaults to 2. To make it recurse indefinitely, pass null.

colors - if true, then the output will be styled with ANSI color codes.

Defaults to false. Colors are customizable;

see customizing util.inspect() colors.

console.error([data][, ...])#

Prints to stderr with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).

const code = 5;

console.error('error #%d', code);

// Prints: error #5, to stderr console.error('error', code);

// Prints: error 5, to stderr

If formatting elements (e.g. %d) are not found in the first string

then util.inspect() is called on each argument and the resulting string values are concatenated. See util.format() for more information.

console.info([data][, ...])#

The console.info() function is an alias for console.log().

console.log([data][, ...])#

Prints to stdout with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).

var count = 5;

console.log('count: %d', count);

// Prints: count: 5, to stdout console.log('count: ', count);

// Prints: count: 5, to stdout

If formatting elements (e.g. %d) are not found in the first string

then util.inspect() is called on each argument and the resulting string values are concatenated. See util.format() for more information.

console.time(label)#

Starts a timer that can be used to compute the duration of an operation.

Timers are identified by a unique label. Use the same label when you callconsole.timeEnd() to stop the timer and output the elapsed time in milliseconds to stdout. Timer durations are accurate to the

sub-millisecond.

console.timeEnd(label)#

Stops a timer that was previously started by calling console.time() and prints the result to stdout:

console.time('100-elements');

for (var i = 0; i < 100; i++) { ;

}

console.timeEnd('100-elements');

// prints 100-elements: 225.438ms

Note: As of Node.js v6.0.0, console.timeEnd() deletes the timer to avoid leaking it. On older versions, the timer persisted. This

allowed console.timeEnd() to be called multiple times for the same label.

This functionality was unintended and is no longer supported.

console.trace(message[, ...])#

Prints to stderr the string 'Trace :', followed by the util.format() formatted message and stack trace to the current position in the code.

console.trace('Show me');

// Prints: (stack trace will vary based on where trace is called) // Trace: Show me

// at repl:2:9

// at REPLServer.defaultEval (repl.js:248:27) // at bound (domain.js:287:14)

// at REPLServer.runBound [as eval] (domain.js:300:12) // at REPLServer.<anonymous> (repl.js:412:12)

// at emitOne (events.js:82:20)

// at REPLServer.emit (events.js:169:7)

// at REPLServer.Interface._onLine (readline.js:210:10) // at REPLServer.Interface._line (readline.js:549:8)

// at REPLServer.Interface._ttyWrite (readline.js:826:14) console.warn([data][, ...])#

The console.warn() function is an alias for console.error().

 Crypto

 Determining if crypto support is unavailable

 Class: Certificate

 new crypto.Certificate()

 certificate.exportChallenge(spkac)

 certificate.exportPublicKey(spkac)

 certificate.verifySpkac(spkac)

 Class: Cipher

 cipher.final([output_encoding])

 cipher.setAAD(buffer)

 cipher.getAuthTag()

 cipher.setAutoPadding(auto_padding=true)

 cipher.update(data[, input_encoding][, output_encoding])

 Class: Decipher

 decipher.final([output_encoding])

 decipher.setAAD(buffer)

 decipher.setAuthTag(buffer)

 decipher.setAutoPadding(auto_padding=true)

 decipher.update(data[, input_encoding][, output_encoding])

 Class: DiffieHellman

 diffieHellman.computeSecret(other_public_key[, input_encoding][, output_encoding])

 diffieHellman.generateKeys([encoding])

 diffieHellman.getGenerator([encoding])

 diffieHellman.getPrime([encoding])

 diffieHellman.getPrivateKey([encoding])

 diffieHellman.getPublicKey([encoding])

 diffieHellman.setPrivateKey(private_key[, encoding])

 diffieHellman.setPublicKey(public_key[, encoding])

 diffieHellman.verifyError

 Class: ECDH

 ecdh.computeSecret(other_public_key[, input_encoding]

[, output_encoding])

 ecdh.generateKeys([encoding[, format]])

 ecdh.getPrivateKey([encoding])

 ecdh.getPublicKey([encoding[, format]])

 ecdh.setPrivateKey(private_key[, encoding])

 ecdh.setPublicKey(public_key[, encoding])

 Class: Hash

 hash.digest([encoding])

 hash.update(data[, input_encoding])

 Class: Hmac

 hmac.digest([encoding])

 hmac.update(data[, input_encoding])

 Class: Sign

 sign.sign(private_key[, output_format])

 sign.update(data[, input_encoding])

 Class: Verify

 verifier.update(data[, input_encoding])

 verifier.verify(object, signature[, signature_format])

 crypto module methods and properties

 crypto.DEFAULT_ENCODING

 crypto.fips

 crypto.createCipher(algorithm, password)

 crypto.createCipheriv(algorithm, key, iv)

 crypto.createCredentials(details)

 crypto.createDecipher(algorithm, password)

 crypto.createDecipheriv(algorithm, key, iv)

 crypto.createDiffieHellman(prime[, prime_encoding][, generator][, generator_encoding])

 crypto.createDiffieHellman(prime_length[, generator])

 crypto.createECDH(curve_name)

 crypto.createHash(algorithm)

 crypto.createHmac(algorithm, key)

 crypto.createSign(algorithm)

 crypto.createVerify(algorithm)

 crypto.getCiphers()

 crypto.getCurves()

 crypto.getDiffieHellman(group_name)

 crypto.getHashes()

 crypto.pbkdf2(password, salt, iterations, keylen, digest, callback)

 crypto.pbkdf2Sync(password, salt, iterations, keylen, digest)

 crypto.privateDecrypt(private_key, buffer)

 crypto.privateEncrypt(private_key, buffer)

 crypto.publicDecrypt(public_key, buffer)

 crypto.publicEncrypt(public_key, buffer)

 crypto.randomBytes(size[, callback])

 crypto.setEngine(engine[, flags])

 Notes

 Legacy Streams API (pre Node.js v0.10)

 Recent ECDH Changes

 Support for weak or compromised algorithms Crypto#

Stability: 2 - Stable

The crypto module provides cryptographic functionality that includes a set of wrappers for OpenSSL's hash, HMAC, cipher, decipher, sign and verify functions.

Use require('crypto') to access this module.

const crypto = require('crypto');

const secret = 'abcdefg';

const hash = crypto.createHmac('sha256', secret) .update('I love cupcakes')

.digest('hex');

console.log(hash);

// Prints:

//

c0fa1bc00531bd78ef38c628449c5102aeabd49b5dc3a2a516ea6ea95 9d6658e

Determining if crypto support is unavailable#

It is possible for Node.js to be built without including support for

the crypto module. In such cases, calling require('crypto') will result in an error being thrown.

var crypto;

try {

crypto = require('crypto');

} catch (err) {

console.log('crypto support is disabled!');

}

Class: Certificate#

SPKAC is a Certificate Signing Request mechanism originally implemented by Netscape and now specified formally as part

of HTML5's keygen element.

The crypto module provides the Certificate class for working with SPKAC data. The most common usage is handling output generated by the HTML5<keygen> element. Node.js uses OpenSSL's SPKAC

implementation internally.

new crypto.Certificate()#

Instances of the Certificate class can be created using the new keyword or by calling crypto.Certificate() as a function:

const crypto = require('crypto');

const cert1 = new crypto.Certificate();

const cert2 = crypto.Certificate();

certificate.exportChallenge(spkac)#

The spkac data structure includes a public key and a challenge.

The certificate.exportChallenge() returns the challenge component in the form of a Node.js Buffer. The spkac argument can be either a string or a Buffer.

const cert = require('crypto').Certificate();

const spkac = getSpkacSomehow();

const challenge = cert.exportChallenge(spkac);

console.log(challenge.toString('utf8'));

// Prints the challenge as a UTF8 string certificate.exportPublicKey(spkac)#

The spkac data structure includes a public key and a challenge.

The certificate.exportPublicKey() returns the public key component in the

form of a Node.js Buffer. The spkac argument can be either a string or a Buffer.

const cert = require('crypto').Certificate();

const spkac = getSpkacSomehow();

const publicKey = cert.exportPublicKey(spkac);

console.log(publicKey);

// Prints the public key as <Buffer ...>

certificate.verifySpkac(spkac)#

Returns true if the given spkac data structure is valid, false otherwise.

The spkac argument must be a Node.js Buffer.

const cert = require('crypto').Certificate();

const spkac = getSpkacSomehow();

console.log(cert.verifySpkac(Buffer.from(spkac)));

// Prints true or false Class: Cipher#

Instances of the Cipher class are used to encrypt data. The class can be used in one of two ways:

 As a stream that is both readable and writable, where plain unencrypted data is written to produce encrypted data on the readable side, or

 Using the cipher.update() and cipher.final() methods to produce the encrypted data.

The crypto.createCipher() or crypto.createCipheriv() methods are used to create Cipher instances. Cipher objects are not to be created directly using the new keyword.

Example: Using Cipher objects as streams:

const crypto = require('crypto');

const cipher = crypto.createCipher('aes192', 'a password');

var encrypted = '';

cipher.on('readable', () => { var data = cipher.read();

if (data)

encrypted += data.toString('hex');

});

cipher.on('end', () => { console.log(encrypted);

// Prints:

ca981be48e90867604588e75d04feabb63cc007a8f8ad89b10616ed84 d815504

});

cipher.write('some clear text data');

cipher.end();

Example: Using Cipher and piped streams:

const crypto = require('crypto');

const fs = require('fs');

const cipher = crypto.createCipher('aes192', 'a password');

const input = fs.createReadStream('test.js');

const output = fs.createWriteStream('test.enc');

input.pipe(cipher).pipe(output);

Example: Using the cipher.update() and cipher.final() methods:

const crypto = require('crypto');

const cipher = crypto.createCipher('aes192', 'a password');

var encrypted = cipher.update('some clear text data', 'utf8', 'hex');

encrypted += cipher.final('hex');

console.log(encrypted);

// Prints:

ca981be48e90867604588e75d04feabb63cc007a8f8ad89b10616ed84 d815504

cipher.final([output_encoding])#

Returns any remaining enciphered contents. If output_encoding parameter is one of 'binary', 'base64' or 'hex', a string is returned. If

anoutput_encoding is not provided, a Buffer is returned.

Once the cipher.final() method has been called, the Cipher object can no longer be used to encrypt data. Attempts to call cipher.final() more than once will result in an error being thrown.

cipher.setAAD(buffer)#

When using an authenticated encryption mode (only GCM is currently supported), the cipher.setAAD() method sets the value used for

the additional authenticated data (AAD) input parameter.

cipher.getAuthTag()#

When using an authenticated encryption mode (only GCM is currently supported), the cipher.getAuthTag() method returns a Buffer containing theauthentication tag that has been computed from the given data.

The cipher.getAuthTag() method should only be called after encryption has been completed using the cipher.final() method.

cipher.setAutoPadding(auto_padding=true)#

When using block encryption algorithms, the Cipher class will

automatically add padding to the input data to the appropriate block size.

To disable the default padding call cipher.setAutoPadding(false).

When auto_padding is false, the length of the entire input data must be a multiple of the cipher's block size or cipher.final() will throw an Error.

Disabling automatic padding is useful for non-standard padding, for instance using 0x0 instead of PKCS padding.

The cipher.setAutoPadding() method must be called before cipher.final().

cipher.update(data[, input_encoding][, output_encoding])#

Updates the cipher with data. If the input_encoding argument is given, it's value must be one of 'utf8', 'ascii', or 'binary' and the dataargument is a

string using the specified encoding. If the input_encoding argument is not given, data must be a Buffer. If data is a Buffer theninput_encoding is ignored.

The output_encoding specifies the output format of the enciphered data, and can be 'binary', 'base64' or 'hex'. If the output_encoding is specified, a string using the specified encoding is returned. If no output_encoding is provided, a Buffer is returned.

The cipher.update() method can be called multiple times with new data until cipher.final() is called. Calling cipher.update() after cipher.final()will result in an error being thrown.

Class: Decipher#

Instances of the Decipher class are used to decrypt data. The class can be used in one of two ways:

 As a stream that is both readable and writable, where plain encrypted data is written to produce unencrypted data on the readable side, or

 Using the decipher.update() and decipher.final() methods to produce the unencrypted data.

The crypto.createDecipher() or crypto.createDecipheriv() methods are used to create Decipher instances. Decipher objects are not to be created directly using the new keyword.

Example: Using Decipher objects as streams:

const crypto = require('crypto');

const decipher = crypto.createDecipher('aes192', 'a password');

var decrypted = '';

decipher.on('readable', () => { var data = decipher.read();

if (data)

decrypted += data.toString('utf8');

});

decipher.on('end', () => {

console.log(decrypted);

// Prints: some clear text data });

var encrypted =

'ca981be48e90867604588e75d04feabb63cc007a8f8ad89b10616ed84 d815504';

decipher.write(encrypted, 'hex');

decipher.end();

Example: Using Decipher and piped streams:

const crypto = require('crypto');

const fs = require('fs');

const decipher = crypto.createDecipher('aes192', 'a password');

const input = fs.createReadStream('test.enc');

const output = fs.createWriteStream('test.js');

input.pipe(decipher).pipe(output);

Example: Using the decipher.update() and decipher.final() methods:

const crypto = require('crypto');

const decipher = crypto.createDecipher('aes192', 'a password');

var encrypted =

'ca981be48e90867604588e75d04feabb63cc007a8f8ad89b10616ed84 d815504';

var decrypted = decipher.update(encrypted, 'hex', 'utf8');

decrypted += decipher.final('utf8');

console.log(decrypted);

// Prints: some clear text data

decipher.final([output_encoding])#

Returns any remaining deciphered contents. If output_encoding parameter is one of 'binary', 'base64' or 'hex', a string is returned. If

anoutput_encoding is not provided, a Buffer is returned.

Once the decipher.final() method has been called, the Decipher object can no longer be used to decrypt data. Attempts to call decipher.final()more than once will result in an error being thrown.

decipher.setAAD(buffer)#

When using an authenticated encryption mode (only GCM is currently supported), the cipher.setAAD() method sets the value used for

the additional authenticated data (AAD) input parameter.

decipher.setAuthTag(buffer)#

When using an authenticated encryption mode (only GCM is currently supported), the decipher.setAuthTag() method is used to pass in the receivedauthentication tag. If no tag is provided, or if the cipher text has been tampered with, decipher.final() with throw, indicating that the cipher text should be discarded due to failed authentication.

decipher.setAutoPadding(auto_padding=true)#

When data has been encrypted without standard block padding,

calling decipher.setAutoPadding(false) will disable automatic padding to preventdecipher.final() from checking for and removing padding.

Turning auto padding off will only work if the input data's length is a multiple of the ciphers block size.

The decipher.setAutoPadding() method must be called before decipher.update().

decipher.update(data[, input_encoding][, output_encoding])#

Updates the decipher with data. If the input_encoding argument is given, it's value must be one of 'binary', 'base64', or 'hex' and the dataargument is a string using the specified encoding. If the input_encoding argument is not given, data must be a Buffer. If data is a Buffer theninput_encoding is ignored.

The output_encoding specifies the output format of the enciphered data, and can be 'binary', 'ascii' or 'utf8'. If the output_encoding is specified, a

string using the specified encoding is returned. If no output_encoding is provided, a Buffer is returned.

The decipher.update() method can be called multiple times with new data until decipher.final() is called.

Calling decipher.update() afterdecipher.final() will result in an error being thrown.

Class: DiffieHellman#

The DiffieHellman class is a utility for creating Diffie-Hellman key exchanges.

Instances of the DiffieHellman class can be created using the crypto.createDiffieHellman() function.

const crypto = require('crypto');

const assert = require('assert');

// Generate Alice's keys...

const alice = crypto.createDiffieHellman(2048);

const alice_key = alice.generateKeys();

// Generate Bob's keys...

const bob = crypto.createDiffieHellman(alice.getPrime(), alice.getGenerator());

const bob_key = bob.generateKeys();

// Exchange and generate the secret...

const alice_secret = alice.computeSecret(bob_key);

const bob_secret = bob.computeSecret(alice_key);

// OK

assert.equal(alice_secret.toString('hex'), bob_secret.toString('hex'));

diffieHellman.computeSecret(other_public_key[, input_encoding][, output_encoding])#

Computes the shared secret using other_public_key as the other party's public key and returns the computed shared secret. The supplied key is interpreted using the specified input_encoding, and secret is encoded

using specified output_encoding. Encodings can be 'binary', 'hex', or'base64'. If the input_encoding is not provided, other_public_key is expected to be a Buffer.

If output_encoding is given a string is returned; otherwise, a Buffer is returned.

diffieHellman.generateKeys([encoding])#

Generates private and public Diffie-Hellman key values, and returns the public key in the specified encoding. This key should be transferred to the other party. Encoding can be 'binary', 'hex', or 'base64'. If encoding is provided a string is returned; otherwise a Buffer is returned.

diffieHellman.getGenerator([encoding])#

Returns the Diffie-Hellman generator in the specified encoding, which can be 'binary', 'hex', or 'base64'. If encoding is provided a string is returned;

otherwise a Buffer is returned.

diffieHellman.getPrime([encoding])#

Returns the Diffie-Hellman prime in the specified encoding, which can be 'binary', 'hex', or 'base64'. If encoding is provided a string is returned;

otherwise a Buffer is returned.

diffieHellman.getPrivateKey([encoding])#

Returns the Diffie-Hellman private key in the specified encoding, which can be 'binary', 'hex', or 'base64'. If encoding is provided a string is returned; otherwise a Buffer is returned.

diffieHellman.getPublicKey([encoding])#

Returns the Diffie-Hellman public key in the specified encoding, which can be 'binary', 'hex', or 'base64'. If encoding is provided a string is returned;

otherwise a Buffer is returned.

diffieHellman.setPrivateKey(private_key[, encoding])#

Sets the Diffie-Hellman private key. If the encoding argument is provided and is either 'binary', 'hex', or 'base64', private_key is expected to be a string. If no encoding is provided, private_key is expected to be a Buffer.

diffieHellman.setPublicKey(public_key[, encoding])#

Sets the Diffie-Hellman public key. If the encoding argument is provided and is either 'binary', 'hex' or 'base64', public_key is expected to be a

Sets the Diffie-Hellman public key. If the encoding argument is provided and is either 'binary', 'hex' or 'base64', public_key is expected to be a

Documento similar