Sei sulla pagina 1di 126

15/8/2015 Acerca de esta documentación Node.js v0.6.

19 Manual & Documentación

es en

Nodejs.es
HOME

DOCS

TRABAJOS
Node.js v0.6.19 Manual & Documentación
GITHUB Índice | Ver todo en una misma página | Ver como JSON

@nodejs_es
Tabla de Contenidos
Acerca de esta documentación
Sitio Índice de estabilidad
Oficial salida JSON
HOME Sinopsis
DESCARGAR Objetos Globales
ACERCA global
REGISTO NPM
process
console
DOCS
Class: Buffer
BLOG
require()
COMUNIDAD
require.resolve()
LOGOS
require.cache
TRABAJOS __filename
__dirname
module
@nodejs
exports
setTimeout(cb, ms)
clearTimeout(t)
setInterval(cb, ms)
clearInterval(t)
console
console.log()
console.info()
console.warn()
console.error()
console.dir(obj)
console.time(label)
console.timeEnd(label)
console.trace()
console.assert()
Timer
setTimeout(callback, delay, [arg], [...])
clearTimeout(timeoutId)
setInterval(callback, delay, [arg], [...])
clearInterval(intervalId)
Módulos
Módulos básicos
Módulo File
Cargando desde la carpeta node_modules
Optimización de proceso de búsqueda en node_modules
Carpetas como módulos
Almacenamiento en la caché

http://nodejs-es.github.io/api/all.html 1/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación
Todos juntos...
Cargar desde las carpetas de require.paths
Nota: Por favor evite la modificación de require.paths
Establecer require.paths a algún otro valor para nada.
Poner rutas relativas en require.paths es... raro.
Cero aislamiento
Addenda: Consejos para administrar paquetes
Addons
process
Evento: 'exit'
Evento: 'uncaughtException'
Eventos de señal
process.stdout
process.stderr
process.stdin
process.argv
process.execPath
process.chdir(directory)
process.cwd()
process.env
process.exit(code=0)
process.getgid()
process.setgid(id)
process.getuid()
process.setuid(id)
process.version
process.installPrefix
process.kill(pid, signal='SIGTERM')
process.pid
process.title
process.platform
process.memoryUsage()
process.nextTick(callback)
process.umask([mask])
util
util.format()
util.debug(string)
util.log(string)
util.inspect(object, showHidden=false, depth=2)
util.isArray(object)
util.isRegExp(object)
util.isDate(object)
util.isError(object)
util.pump(readableStream, writableStream, [callback])
util.inherits(constructor, superConstructor)
Eventos
events.EventEmitter
emitter.addListener(event, listener)
emitter.on(event, listener)
emitter.once(event, listener)
emitter.removeListener(event, listener)
emitter.removeAllListeners(event)
emitter.setMaxListeners(n)
emitter.listeners(event)
emitter.emit(event, [arg1], [arg2], [...])
Event: 'newListener'
Buffer
http://nodejs-es.github.io/api/all.html 2/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación
Class: Buffer
new Buffer(size)
new Buffer(array)
new Buffer(str, [encoding])
buf.write(string, [offset], [length], [encoding])
buf.toString([encoding], [start], [end])
buf[index]
Class Method: Buffer.isBuffer(obj)
Class Method: Buffer.byteLength(string, [encoding])
buf.length
buf.copy(targetBuffer, [targetStart], [sourceStart], [sourceEnd])
buf.slice([start], [end])
buf.readUInt8(offset, [noAssert])
buf.readUInt16LE(offset, [noAssert])
buf.readUInt16BE(offset, [noAssert])
buf.readUInt32LE(offset, [noAssert])
buf.readUInt32BE(offset, [noAssert])
buf.readInt8(offset, [noAssert])
buf.readInt16LE(offset, [noAssert])
buf.readInt16BE(offset, [noAssert])
buf.readInt32LE(offset, [noAssert])
buf.readInt32BE(offset, [noAssert])
buf.readFloatLE(offset, [noAssert])
buf.readFloatBE(offset, [noAssert])
buf.readDoubleLE(offset, [noAssert])
buf.readDoubleBE(offset, [noAssert])
buf.writeUInt8(value, offset, [noAssert])
buf.writeUInt16LE(value, offset, [noAssert])
buf.writeUInt16BE(value, offset, [noAssert])
buf.writeUInt32LE(value, offset, [noAssert])
buf.writeUInt32BE(value, offset, [noAssert])
buf.writeInt8(value, offset, [noAssert])
buf.writeInt16LE(value, offset, [noAssert])
buf.writeInt16BE(value, offset, [noAssert])
buf.writeInt32LE(value, offset, [noAssert])
buf.writeInt32BE(value, offset, [noAssert])
buf.writeFloatLE(value, offset, [noAssert])
buf.writeFloatBE(value, offset, [noAssert])
buf.writeDoubleLE(value, offset, [noAssert])
buf.writeDoubleBE(value, offset, [noAssert])
buf.fill(value, [offset], [end])
buffer.INSPECT_MAX_BYTES
Class: SlowBuffer
Streams
Readable Stream
Event: 'data'
Event: 'end'
Event: 'error'
Event: 'close'
Event: 'fd'
stream.readable
stream.setEncoding(encoding)
stream.pause()
stream.resume()
stream.destroy()
stream.destroySoon()
stream.pipe(destination, [options])
http://nodejs-es.github.io/api/all.html 3/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación
Writable Stream
Event: 'drain'
Event: 'error'
Event: 'close'
Event: 'pipe'
stream.writable
stream.write(string, encoding='utf8', [fd])
stream.write(buffer)
stream.end()
stream.end(string, encoding)
stream.end(buffer)
stream.destroy()
stream.destroySoon()
Crypto
crypto.createCredentials(details)
crypto.createHash(algorithm)
Class: Hash
hash.update(data)
hash.digest([encoding])
crypto.createHmac(algorithm, key)
Class: Hmac
hmac.update(data)
hmac.digest(encoding='binary')
crypto.createCipher(algorithm, key)
crypto.createCipheriv(algorithm, key, iv)
Class: Cipher
cipher.update(data, [input_encoding], [output_encoding])
cipher.final([output_encoding])
cipher.setAutoPadding(auto_padding=true)
crypto.createDecipher(algorithm, key)
decipher.update(data, input_encoding='binary', output_encoding='binary')
Class: Decipher
decipher.update(data, [input_encoding], [output_encoding])
decipher.final([output_encoding])
decipher.setAutoPadding(auto_padding=true)
crypto.createSign(algorithm)
Class: Signer
signer.update(data)
signer.sign(private_key, output_format='binary')
crypto.createVerify(algorithm)
Class: Verify
verifier.update(data)
verifier.verify(cert, signature, signature_format='binary')
crypto.createDiffieHellman(prime_length)
crypto.createDiffieHellman(prime, [encoding])
Class: DiffieHellman
diffieHellman.generateKeys([encoding])
diffieHellman.computeSecret(other_public_key, [input_encoding], [output_encoding])
diffieHellman.getPrime([encoding])
diffieHellman.getGenerator([encoding])
diffieHellman.getPublicKey([encoding])
diffieHellman.getPrivateKey([encoding])
diffieHellman.setPublicKey(public_key, [encoding])
diffieHellman.setPrivateKey(public_key, [encoding])
crypto.getDiffieHellman(group_name)
crypto.pbkdf2(password, salt, iterations, keylen, callback)
crypto.randomBytes(size, [callback])
http://nodejs-es.github.io/api/all.html 4/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación
TLS (SSL)
s = tls.connect(port, [host], [options], callback)
STARTTLS
tls.Server
tls.createServer(options, secureConnectionListener)
Event: 'secureConnection'
server.listen(port, [host], [callback])
server.close()
server.maxConnections
server.connections
File System
fs.rename(path1, path2, [callback])
fs.renameSync(path1, path2)
fs.truncate(fd, len, [callback])
fs.truncateSync(fd, len)
fs.chmod(path, mode, [callback])
fs.chmodSync(path, mode)
fs.stat(path, [callback])
fs.lstat(path, [callback])
fs.fstat(fd, [callback])
fs.statSync(path)
fs.lstatSync(path)
fs.fstatSync(fd)
fs.link(srcpath, dstpath, [callback])
fs.linkSync(srcpath, dstpath)
fs.symlink(linkdata, path, [callback])
fs.symlinkSync(linkdata, path)
fs.readlink(path, [callback])
fs.readlinkSync(path)
fs.realpath(path, [callback])
fs.realpathSync(path)
fs.unlink(path, [callback])
fs.unlinkSync(path)
fs.rmdir(path, [callback])
fs.rmdirSync(path)
fs.mkdir(path, mode, [callback])
fs.mkdirSync(path, mode)
fs.readdir(path, [callback])
fs.readdirSync(path)
fs.close(fd, [callback])
fs.closeSync(fd)
fs.open(path, flags, [mode], [callback])
fs.openSync(path, flags, [mode])
fs.write(fd, buffer, offset, length, position, [callback])
fs.writeSync(fd, buffer, offset, length, position)
fs.writeSync(fd, str, position, encoding='utf8')
fs.read(fd, buffer, offset, length, position, [callback])
fs.readSync(fd, buffer, offset, length, position)
fs.readSync(fd, length, position, encoding)
fs.readFile(filename, [encoding], [callback])
fs.readFileSync(filename, [encoding])
fs.writeFile(filename, data, encoding='utf8', [callback])
fs.writeFileSync(filename, data, encoding='utf8')
fs.watchFile(filename, [options], listener)
fs.unwatchFile(filename)
fs.Stats
fs.ReadStream
http://nodejs-es.github.io/api/all.html 5/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación
fs.createReadStream(path, [options])
fs.WriteStream
Event: 'open'
fs.createWriteStream(path, [options])
Path
path.normalize(p)
path.join([path1], [path2], [...])
path.resolve([from ...], to)
path.relative(from, to)
path.dirname(p)
path.basename(p, [ext])
path.extname(p)
net
net.createServer([options], [connectionListener])
net.connect(options, [connectionListener])
net.createConnection(options, [connectionListener])
net.connect(port, [host], [connectListener])
net.createConnection(port, [host], [connectListener])
net.connect(path, [connectListener])
net.createConnection(path, [connectListener])
Class: net.Server
server.listen(port, [host], [listeningListener])
server.listen(path, [listeningListener])
server.close([cb])
server.address()
server.maxConnections
server.connections
Event: 'listening'
Event: 'connection'
Event: 'close'
Event: 'error'
Class: net.Socket
new net.Socket([options])
socket.connect(port, [host], [connectListener])
socket.connect(path, [connectListener])
socket.bufferSize
socket.setEncoding([encoding])
socket.write(data, [encoding], [callback])
socket.end([data], [encoding])
socket.destroy()
socket.pause()
socket.resume()
socket.setTimeout(timeout, [callback])
socket.setNoDelay([noDelay])
socket.setKeepAlive([enable], [initialDelay])
socket.address()
socket.remoteAddress
socket.remotePort
socket.bytesRead
socket.bytesWritten
Event: 'connect'
Event: 'data'
Event: 'end'
Event: 'timeout'
Event: 'drain'
Event: 'error'
Event: 'close'
http://nodejs-es.github.io/api/all.html 6/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación
net.isIP(input)
net.isIPv4(input)
net.isIPv6(input)
UDP / Sockets de Datagrama
Evento: 'message'
Evento: 'listening'
Evento: 'close'
dgram.createSocket(type, [callback])
dgram.send(buf, offset, length, path, [callback])
dgram.send(buf, offset, length, port, address, [callback])
dgram.bind(path)
dgram.bind(port, [address])
dgram.close()
dgram.address()
dgram.setBroadcast(flag)
dgram.setTTL(ttl)
dgram.setMulticastTTL(ttl)
dgram.setMulticastLoopback(flag)
dgram.addMembership(multicastAddress, [multicastInterface])
dgram.dropMembership(multicastAddress, [multicastInterface])
DNS
dns.lookup(domain, [family], callback)
dns.resolve(domain, [rrtype], callback)
dns.resolve4(domain, callback)
dns.resolve6(domain, callback)
dns.resolveMx(domain, callback)
dns.resolveTxt(domain, callback)
dns.resolveSrv(domain, callback)
dns.reverse(ip, callback)
dns.resolveNs(domain, callback)
dns.resolveCname(domain, callback)
HTTP
http.Server
Evento: 'request'
Evento: 'connection'
Evento: 'close'
Evento: 'request'
Evento: 'checkContinue'
Evento: 'upgrade'
Evento: 'clientError'
http.createServer(requestListener)
server.listen(port, [hostname], [callback])
server.listen(path, [callback])
server.close()
http.ServerRequest
Event: 'data'
Event: 'end'
request.method
request.url
request.headers
request.trailers
request.httpVersion
request.setEncoding(encoding=null)
request.pause()
request.resume()
request.connection
http.ServerResponse
http://nodejs-es.github.io/api/all.html 7/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación
response.writeContinue()
response.writeHead(statusCode, [reasonPhrase], [headers])
response.statusCode
response.setHeader(name, value)
response.getHeader(name)
response.removeHeader(name)
response.write(chunk, encoding='utf8')
response.addTrailers(headers)
response.end([data], [encoding])
http.request(options, callback)
http.get(options, callback)
http.Agent
http.getAgent(host, port)
Event: 'upgrade'
Event: 'continue'
agent.maxSockets
agent.sockets
agent.queue
http.ClientRequest
Event 'response'
request.write(chunk, encoding='utf8')
request.end([data], [encoding])
request.abort()
http.ClientResponse
Event: 'data'
Event: 'end'
response.statusCode
response.httpVersion
response.headers
response.trailers
response.setEncoding(encoding=null)
response.pause()
response.resume()
HTTPS
Class: https.Server
https.createServer(options, [requestListener])
https.request(options, callback)
https.get(options, callback)
Class: https.Agent
https.globalAgent
URL
url.parse(urlStr, [parseQueryString], [slashesDenoteHost])
url.format(urlObj)
url.resolve(from, to)
Cadena de consulta
querystring.stringify(obj, sep='&', eq='=')
querystring.parse(str, sep='&', eq='=')
querystring.escape
querystring.unescape
Readline
createInterface(input, output, completer)
interface.setPrompt(prompt, length)
interface.prompt()
interface.question(query, cb)
interface.close()
interface.pause()
interface.resume()
http://nodejs-es.github.io/api/all.html 8/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación
interface.write()
REPL
repl.start([prompt], [stream], [eval], [useGlobal], [ignoreUndefined])
Características de REPL
Executing JavaScript
vm.runInThisContext(code, [filename])
vm.runInNewContext(code, [sandbox], [filename])
vm.runInContext(code, context, [filename])
vm.createContext([initSandbox])
vm.createScript(code, [filename])
Class: Script
script.runInThisContext()
script.runInNewContext([sandbox])
Child Process
Class: ChildProcess
Evento: 'exit'
Event: 'disconnect'
child.stdin
child.stdout
child.stderr
child.pid
child.kill([signal])
child.send(message, [sendHandle])
child_process.spawn(command, [args], [options])
child_process.exec(command, [options], callback)
child_process.execFile(file, args, options, callback)
child_process.fork(modulePath, [args], [options])
Assert
assert.fail(actual, expected, message, operator)
assert.ok(value, [message])
assert.equal(actual, expected, [message])
assert.notEqual(actual, expected, [message])
assert.deepEqual(actual, expected, [message])
assert.notDeepEqual(actual, expected, [message])
assert.strictEqual(actual, expected, [message])
assert.notStrictEqual(actual, expected, [message])
assert.throws(block, [error], [message])
assert.doesNotThrow(block, [error], [message])
assert.ifError(value)
TTY (Terminal)
tty.open(path, args=[])
tty.isatty(fd)
tty.setRawMode(mode)
tty.setWindowSize(fd, row, col)
tty.getWindowSize(fd)
Zlib
Examples
Constants
zlib.createGzip([options])
zlib.createGunzip([options])
zlib.createDeflate([options])
zlib.createInflate([options])
zlib.createDeflateRaw([options])
zlib.createInflateRaw([options])
zlib.createUnzip([options])
Class: zlib.Gzip
Class: zlib.Gunzip
http://nodejs-es.github.io/api/all.html 9/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación
Class: zlib.Deflate
Class: zlib.Inflate
Class: zlib.DeflateRaw
Class: zlib.InflateRaw
Class: zlib.Unzip
Convenience Methods
zlib.deflate(buf, callback)
zlib.deflateRaw(buf, callback)
zlib.gzip(buf, callback)
zlib.gunzip(buf, callback)
zlib.inflate(buf, callback)
zlib.inflateRaw(buf, callback)
zlib.unzip(buf, callback)
Options
Memory Usage Tuning
Módulo os
os.hostname()
os.type()
os.release()
os.uptime()
os.loadavg()
os.totalmem()
os.freemem()
os.cpus()
Depurador
Watchers
Commands reference
Stepping
Breakpoints
Info
Execution control
Various
Uso avanzado
Cluster
cluster.settings
cluster.isMaster
cluster.isWorker
Event: 'fork'
Event: 'online'
Event: 'listening'
Event: 'death'
Event: 'setup'
cluster.setupMaster([settings])
cluster.fork([env])
cluster.settings
cluster.workers
Class: Worker
worker.uniqueID
worker.process
worker.suicide
worker.send(message, [sendHandle])
worker.destroy()
Event: 'message'
Event: 'online'
Event: 'listening'
Event: 'death'
Apéndice 1 - Módulos de terceros
http://nodejs-es.github.io/api/all.html 10/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

Acerca de esta documentación #


El objetivo de este documento es explicar íntegralmente la API Node.js, tanto como una referencia, como así
también un punto de vista conceptual. Cada sección describe un módulo integrado (built-in module) o un
concepto de alto nivel (high-level concept).

En su caso, los tipos de propiedades, los argumentos de métodos, y los argumentos proporcionados a los
controladores de eventos se detallan en una lista debajo de la cabecera del topic.

Cada documento .html tiene un documento correspondiente .json presentando la misma información de
una manera estructurada. Esta característica es experimental, y se agrega para el beneficio de las IDEs y otras
utilidades que desean hacer cosas programáticas con la documentación.

Cada archivo .html y .json es generado en base al correspondiente archivo .markdown de la carpeta
doc/api en el árbol del código fuente de node. La documentación es generada utilizando el programa
tools/doc/generate.js . La plantilla html esta ubicada en doc/template.html .

Índice de estabilidad #
A lo largo de la documentación verá las indicaciones de estabilidad de cada sección. La API Node.js es algo
cambiante, y a medida que madura, ciertas partes son más confiables que otras. Algunas están tan probados, y
son tan confiables que es poco probable que cambien en lo absoluto. Otros son completamente nuevos y
experimentales, o se considera peligroso y en proceso de ser rediseñado.

Los avisos se parecen a esto:

Stability: 1 Experimental

Los índices de estabilidad son los siguientes:

0 ­ Deprecated Esta característica es conocida como problemática y ya se han previsto cambios. No confíe
en esto. El uso de esta característica puede causar advertencias.

1 ­ Experimental Esta característica se ha incluído recientemente y puede cambiar o ser removida en


futuras versiones. Por favor, pruébela y de feedback. Si esta dirige a un caso de uso importante para usted,
hágalo saber al equipo principal de node.

2 ­ Unstable La API está en proceso de resolución, pero todavia no ha sido suficientemente testeada en el
mundo real para ser considerada estable. Si es razonable se mantendrá compatiblidad con versiones
anteriores.

3 ­ Stable La API ha resultado satisfactoria pero limpiar en el código subyacente puede causar pequeños
cambios. Esta garantizada la compatibilidad con versiones anteriores.

4 ­ API Frozen La API ha sido testeada ampliamente en producción y es poco provable que alguna vez
tenga cambios.

5 ­ Locked Al menos que sean encontrados serios bugs este código nunca cambiará. Por favor no sugiera
cambios en esta parte, serán rechazados.

salida JSON #

Stability: 1 - Experimental

Cada archivo HTML en el markdown tiene un correspondiente archivo JSON con los mismos datos.

http://nodejs-es.github.io/api/all.html 11/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación
Esta característica se agregó a partir de node v0.6.12. Es experimental.

Sinopsis #
Un ejemplo de un servidor web escrito en Node que responde con 'Hola mundo':

var http = require('http');

http.createServer(function (request, response) {


response.writeHead(200, {'Content-Type': 'text/plain'});
response.end('Hola mundo\n');
}).listen(8124);

console.log('Servidor ejecutándose en http://127.0.0.1:8124/');

Para ejecutar el servidor, copie el código en un fichero llamado example.js y ejecútelo con el programa node

> node example.js


Servidor ejecutándose en http://127.0.0.1:8124/

Todos los ejemplos en está documentación son ejecutados de manera similar.

Objetos Globales #
Estos objectos estan disponibles en todos los módulos. Algunos de estos objetos no están en el ámbito global pero
si a nivel módulo - Tómelo en cuenta.

global #
{Object} El namespace del objeto global.

En los navegadores, el ambito del nivel superior es el ambito global. Esto significa que en los navegadores si tu
estas en el ambito global var something definirá una variable. En Node esto es diferente. El ambito del nivel
superior no es el ambito global; var something dentro de un módulo de node será local para este módulo.

process #
{Object}

El objeto process. Véase la sección objeto process.

console #
{Object}

Usado para la salida de pantalla de stdout y stderr. Véase la sección stdio

Class: Buffer #
{Function}
http://nodejs-es.github.io/api/all.html 12/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación
Utilizado para manejar datos binarios . Véase la sección buffer.

require() #
{Function}

Para requerir módulos. Véase la sección Módules. require no es global sino más bien local para cada módulo.

require.resolve() #
Usa el mecanismo interno de require() para buscar la localización de un módulo, pero en lugar de cargar el
módulo, solo devuelve el nombre del fichero que lo contiene.

require.cache #
Object

Modules are cached in this object when they are required. By deleting a key value from this object, the next
require will reload the module.

__filename #
{String}

El nombre del fichero que contiene al script que esta siendo ejecutado. Este esta definido como ruta absoluta, y
no es necesariamente el mismo nombre del fichero pasado como argumento en la linea de comando. El valor
dentro del módulo es la ruta al mismo.

Ejemplo: Ejecutando node example.js desde /User/mjr

console.log(__filename);
// /Users/mjr/example.js

__filename isn't actually a global but rather local to each module.

__dirname #
{String}

El nombre del directorio del script que esta siendo ejecutado.

Ejemplo:Ejecutando node example.js desde /User/mjr

console.log(__dirname);
// /Users/mjr

__dirname isn't actually a global but rather local to each module.

module #
{Object}

http://nodejs-es.github.io/api/all.html 13/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación
Una referencia al actual módulo. En particular module.exports es igual al objeto exports . module isn't
actually a global but rather local to each module.

Véase la documentación del sistema de módulos para más información.

exports #
An object which is shared between all instances of the current module and made accessible through require() .
exports is the same as the module.exports object. exports isn't actually a global but rather local to each
module.

See the module system documentation for more information.

See the module section for more information.

setTimeout(cb, ms) #
clearTimeout(t) #
setInterval(cb, ms) #

clearInterval(t) #
The timer functions are global variables. See the timers section.

console #

Stability: 4 - API Frozen

{Object}

For printing to stdout and stderr. Similar to the console object functions provided by most web browsers, here
the output is sent to stdout or stderr.

console.log() #
Prints to stdout with newline. This function can take multiple arguments in a printf() -like way. Example:

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

If formatting elements are not found in the first string then util.inspect is used on each argument. See
util.format() for more information.

console.info() #
Same as console.log .

console.warn() #
console.error() #
Same as console.log but prints to stderr.

http://nodejs-es.github.io/api/all.html 14/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

console.dir(obj) #
Uses util.inspect on obj and prints resulting string to stderr.

console.time(label) #
Mark a time.

console.timeEnd(label) #
Finish timer, record output. Example

console.time('100-elements');
for (var i = 0; i < 100; i++) {
;
}
console.timeEnd('100-elements');

console.trace() #
Print a stack trace to stderr of the current position.

console.assert() #
Same as assert.ok() .

Timer #

setTimeout(callback, delay, [arg], [...]) #


Para programar la ejecución de callback después de delay milisegundos. Devuelve un timeoutId para un
posible uso con clearTimeout() . Opcionalmente, tu puedes también pasar argumentos al callback.

clearTimeout(timeoutId) #
Evita la ejecución de un callback por uno de sus disparadores.

setInterval(callback, delay, [arg], [...]) #


Para programar la repetición repetitiva de un callback cada delay milisegundos. Devuelve un intervalId
para un posible uso con clearInterval() . Opcionalmente, tu puedes también pasar argumentos al callback.

clearInterval(intervalId) #
Evita la ejecución de un callback por uno de sus disparadores.

Módulos #

http://nodejs-es.github.io/api/all.html 15/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación
Node posee un secillo sistema de carga. En Node, los ficheros y módulos son de correspondencia biunívoca. A
modo de ejemplo, foo.js carga el módulo circle.js en el mismo directorio.

El contenido de foo.js :

var circle = require('./circle.js');


console.log( 'El área de un círculo con radio 4 es '
+ circle.area(4));

El contenido de circle.js :

var PI = Math.PI;

exports.area = function (r) {


return PI * r * r;
};

exports.circumference = function (r) {


return 2 * PI * r;
};

El módulo circle.js ha exportado las functiones area() y circumference() . Para exportar a un objeto,
debe añadir el objeto especial exports .

Las variables locales del módulo serán privadas. En este ejemplo la variable PI es privada en circle.js .

Módulos básicos #
Node posee varios módulos compilados en binario. Estos módulos son descritos con más detalle en las siguientes
secciones del documento.

Los módulos básicos son definidos en el código fuente de node en la carpeta lib/ .

Los módulos básicos tienen la preferencia de cargarse primero si su indentificador es pasado desde require() .
Por ejemplo, require('http') siempre devolverá lo construido en el módulo HTTP, incluso si hay un fichero
con ese nombre.

Módulo File #
Si el nombre exacto del fichero no es encontrado, entonces node intentará cargar el nombre del fichero seguido
de la extensión .js , y a continuación con .node .

Los ficheros .js son interpretados como ficheros de texto en JavaScript, y los ficheros .node son
interpretados como extensiones de módulos compilados cargados con dlopen .

Un módulo con el prefijo '/' indica la ruta absoluta al fichero. Por ejemplo,
require('/home/marco/foo.js') cargará el fichero en /home/marco/foo.js .

Un módulo con el prefijo './' es relativo al fichero llamado con require() . Es decir, circle.js debe estar
en el mismo directorio que foo.js para que require('./circle') lo encuentre.

Si se omite el uso de '/' o './' en el fichero, el módulo puede ser un "módulo básico" o se cargará desde la carpeta
node_modules .

http://nodejs-es.github.io/api/all.html 16/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

Cargando desde la carpeta node_modules #


Si el identificador del módulo pasa a require() no es un módulo nativo, y no comienza con '/' , '../' , o
'./' , entonces node inicia en el directorio principal del módulo actual, y añade /node_modules , e intenta
cargar el módulo desde esa ubicación.

Si no se encuentra, entonces se dirige al directorio principal, y así sucesivamente, hasta que el módulo es
encontrado, hasta en la raíz del árbol es encontrado.

Por ejemplo, si el fichero en '/home/ry/projects/foo.js' es llamado como require('bar.js') , entonces


node buscaría en las siguientes ubicaciones, en este orden:

/home/ry/projects/node_modules/bar.js
/home/ry/node_modules/bar.js
/home/node_modules/bar.js
/node_modules/bar.js

Esto permite que los programas encuentren sus dependencias, de modo que no entren en conflicto.

Optimización de proceso de búsqueda en node_modules #


Cuando existen muchos niveles de dependencias anidadas, es posible que los árboles de directorios tomen
bastante tiempo. Las siguientes optimizaciones se realizan para este proceso.

Primero, /node_modules no debe ser anexado a una carpeta ya que termina en /node_modules .

Segundo, si el fichero es llamado con require() ya esta en la jerarquía de node_modules , entonces el nivel
superior de la carpeta node_modules es tratada como la raíz del árbol de búsqueda.

For example, if the file at '/home/ry/projects/foo/node_modules/bar/node_modules/baz/quux.js'


called require('asdf.js') , then node would search the following locations:

Por ejemplo, si el fichero en '/home/ry/projects/foo/node_modules/bar/node_modules/baz/quux.js'


llama como require('asdf.js') , entonces node buscaría en las siguientes ubicaciones:

/home/ry/projects/foo/node_modules/bar/node_modules/baz/node_modules/asdf.js
/home/ry/projects/foo/node_modules/bar/node_modules/asdf.js
/home/ry/projects/foo/node_modules/asdf.js

Carpetas como módulos #


Es conveniente organizar los programas y librerías en los mismos directorios, y proporcionar un único punto de
entrar a la biblioteca. Existe tres formas en donde una carpeta pueda usar require() como un argumento.

Lo primero es crear el fichero package.json en la raíz de la carpeta, que especifique el módulo main . Un
ejemplo de package.json podría verse como esto:

{ "name" : "some-library",
"main" : "./lib/some-library.js" }

Si fuera una carpeta en ./some-library , entonces require('./some-library') trataría de cargar


./some-library/lib/some-library.js .

Este es el mayor grado de conciencia de Node con el fichero package.json .

http://nodejs-es.github.io/api/all.html 17/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación
Si no hay ningún fichero package.json presente en el directorio, entonces node intentará cargar el fichero
index.js o index.node de ese directorio. Por ejemplo, si no hay ninguín fichero package.json en el ejemplo
anterior, entonces require('./some-library') intentará cargar:

./some-library/index.js
./some-library/index.node

Almacenamiento en la caché #
Los módulos se alamacenan en la caché después que fueron cargados por primera vez. Esto significa (entre otras
cosas) que todas las llamadas a require('foo') devuelve el mismo ojecto exacto, si se resolvería en el mismo
fichero

Todos juntos... #
Para obtener el nombre exacto del fichero que se cargará cuando se llame con require() , use la función
require.resolve() .

Uniendo todo lo anterior, aquí se muestra un algoritmo de alto nievel en pseudocódigo de lo que haría
require.resolve :

require(X)
1. Si X es módulo básico,
a. devolver el módulo básico
b. STOP
2. Si X inicia con con `./` or `/`,
a. LOAD_AS_FILE(Y + X)
b. LOAD_AS_DIRECTORY(Y + X)
3. LOAD_NODE_MODULES(X, dirname(Y))
4. THROW "not found"

LOAD_AS_FILE(X)
1. Si X es un fichero, cargar X como texto JavaScript. STOP
2. Si X.js es un fichero, cargar X.js como texto JavaScript. STOP
3. Si X.node es un fichero, cargar X.node como extensión binaria. STOP

LOAD_AS_DIRECTORY(X)
1. Si X/package.json es un fichero,
a. Parsear X/package.json, y buscar el campo "main".
b. let M = X + (json main field)
c. LOAD_AS_FILE(M)
2. LOAD_AS_FILE(X/index)

LOAD_NODE_MODULES(X, START)
1. let DIRS=NODE_MODULES_PATHS(START)
2. for each DIR in DIRS:
a. LOAD_AS_FILE(DIR/X)
b. LOAD_AS_DIRECTORY(DIR/X)

NODE_MODULES_PATHS(START)
1. let PARTS = path split(START)
2. let ROOT = index es una instancia de "node_modules" en PARTS, o 0
3. let I = count of PARTS - 1
4. let DIRS = []
5. while I > ROOT,
a. if PARTS[I] = "node_modules" CONTINUE
c. DIR = path join(PARTS[0 .. I] + "node_modules")

http://nodejs-es.github.io/api/all.html 18/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación
b. DIRS = DIRS + DIR
6. return DIRS

Cargar desde las carpetas de require.paths #


En node, require.paths es un array de strings que representa las rutas de acceso a los módulos cuando estos
no tienen el prefijo '/' , './' , o '../' . Por ejemplo, si establece require.paths como:

[ '/home/micheil/.node_modules',
'/usr/local/lib/node_modules' ]

A continuación se llama a require('bar/baz.js') y buscará en las siguientes ubicaciones:

1: '/home/micheil/.node_modules/bar/baz.js'
2: '/usr/local/lib/node_modules/bar/baz.js'

El array en require.paths puede ser transformado en tiempo de ejecución para modificar este
comportamiento.

Se establece inicialmente la variable de entorno NODE_PATH , que contiene una lista delimitada por dos puntos
de rutas exactas. En el anterior ejemplo, la variable de entorno NODE_PATH puedo haber sido establecido como:

/home/micheil/.node_modules:/usr/local/lib/node_modules

Cargar las ubicaciones desde require.paths sólo se realiza si el módulon no se ha encontrado desde el
algoritmo node_modules . Los módulos globarles son de baja prioridad para las dependencias de los paquetes.

Nota: Por favor evite la modificación de require.paths #


Por razones de compatibilidad, require.paths sigue siendo la primera prioridad en el proceso de búsqueda de
módulos. Sin embargo, puede desaparecer en una próxima versión.

Aunque parecía una buena idea en aquel tiempo, y ha permitido ser un experimento muy útil, en la práctica la
transformación de require.paths es una lista a menudo con problemas y dolores de cabeza.

Establecer require.paths a algún otro valor para nada. #

Esto no hace nada de lo que se podría esperar:

require.paths = [ '/usr/lib/node' ];

Todo lo que se hace aquí es perder la referencia actual de node en la búsqueda de rutas, y crea una nueva
referencia a otra cosa que no sirve para nada.

Poner rutas relativas en require.paths es... raro. #

Si hace esto:

require.paths.push('./lib');

entonces no añada la ruta completa donde se resolvió ./lib en este sistema de ficheros. En cambio, esto añade

http://nodejs-es.github.io/api/all.html 19/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

literalmente './lib' , lo que significa si hace require('y.js') en /a/b/x.js , entonces se ve en


/a/b/lib/y.js . Si a continuación se usa require('y.js') en /l/m/n/o/p.js , entonces se ve en
/l/m/n/o/lib/y.js .

En la práctica, las personas han usado esto de una manera ad hoc para la dependencia de paquetes, pero esta
técnica es frágil.

Cero aislamiento #

Existe (debido a un diseño lamentable), sólo un array require.paths utilizado para todos los módulos.

Como resultado, si un programa en node trata de confiar de este comportamiento, es posible que de manera
permanente y sutilmente altere el comportamiento de todos los programas escritos en node el mismo proceso. A
media que el stack crece, y se reune más funcionalidades, ya que esto es un problema con las partes que
interactúan en forma difíciles de predecir.

Addenda: Consejos para administrar paquetes #


La semántica de Node en la función require() fue diseñada para ser lo suficientemente general para soportar
una serie de esctructuras de directorios. Los paquetes de programas como dpkg , rpm , y npm se esperan que
sean construidos como paquetes nativos desde los módulos de Node sin modificaciones.

A continuación sugerimos una estructura en la que puede trabajar:

Supongamos que se desea tener en /usr/lib/node/<some-package>/<some-version> se mantenga el


contenido de una versión específica de un paquete.

Los paquetes pueden depender uno del otro. Con el fin de instalar el paquete foo , puede que tenga que instalar
una versión específica del paquete bar . El paquete bar puede tener dependencias, y en algunos casos, estas
dependencias, incluso pueden entrar en conflicto o crear ciclos.

Desde la búsqueda con Node de la ruta de cualquier módulo cargado (es decir, resueltos los enlaces
simbólicos), y luego de buscar sus dependencias en la carpeta node_modules como se describió anteriormente,
esta situación es muy simple de resolver con la siguiente arquitectura:

/usr/lib/node/foo/1.2.3/ - Contenido del paquete foo, versión 1.2.3.


/usr/lib/node/bar/4.3.2/ - Contenido del paquete bar que es dependencia de foo.
/usr/lib/node/foo/1.2.3/node_modules/bar - Enlace simbólico a /usr/lib/node/bar/4.3.2/.
/usr/lib/node/bar/4.3.2/node_modules/* - Enlaces simbólicos a los paquetes que bar depende.

Por lo tanto, incluso si se encuentra, o si hay problemas de dependencias, cada módulo será capza de obtener una
versión de su dependencia para ser utilizada.

Cuando el código en el paquete foo utiliza require('bar') , se obtendrá la versión al enlace simbólico en
/usr/lib/node/foo/1.2.3/node_modules/bar . Luego, cuando el código del paquete bar llame a
require('quux') , obtendrá la versión simbólica en /usr/lib/node/bar/4.3.2/node_modules/quux .

Además, para hacer el proceso de búsqueda del módulo aún más óptima, en lugar de poner los paquetes
directamente en /usr/lib/node , se puede poner estos en /usr/lib/node_modules/<name>/<version> .
Entonces node no se molestará en buscar por dependencias no encontradas en /usr/node_modules o
/node_modules .

A fin de que los módulos disponibles para node en REPL, puedan ser útiles, añade también la carpeta
/usr/lib/node_modules a la variable de entorno $NODE_PATH . Desde el módulo de búsquedas usando la
carpeta node_modules donde todo es relativo, y basado en la ruta real de los ficheros llamados por
require() , los paquetes pueden ser llamado desde cualquier lugar.

http://nodejs-es.github.io/api/all.html 20/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

Addons #
Addons son objetos enlazados dinamicamente. Ellos pueden ser el pegamento entre las librerias C y C++ con
NodeJS. La API (en estos momentos) es algo compleja, siendo necesario el conocimiento de varias librerias.

V8 JavaScript, una libreria C++. Usada como interfaz con JavaScript: creación de objetos, llamada a
funciones, etc. Documentada extensamente en fichero de cabecera v8.h ( deps/v8/include/v8.h en el
arbol de fuentes de Node).
libev, C libreria para crear un bucle de evento. En cualquier momentos que sea necesario esperar para que
el descriptor de un fichero llegue a ser legible, esperar por un timer, o esperar por una señal, que llevarlo a
cabo será necesario utilizar el intefez de libev. Esto es, si tu realizas cualquier I/O, necesitaras usar libev.
Node usa en bucle de evento EV_DEFAULT . La documentación puede ser encontrada aqui.
libie, librería para manejar el pool de las hebras. Usado para hacer llamadas bloqueantes POSIX del sistema
de forma asincrona. Una amplia variedad de envolturas ya existe para cada llamada, en src/file.cc por
lo que posiblemente no tengas que usarla. Si necesitas usarla echale un vistazo al fichero de cabecera
deps/libie/eio.h .
Librerias internas de Node. La más importante es la clase node::ObjectWrap que probablemente de la
que tu desearas heredar.
Otras. Mira en deps/ para cualquier cosa disponible.

Node estáticamente compila todas las dependencias dentro del ejecutable. Cuando compiles tú módulo, tu no
tendrás que preocuparte sobre enlazar ninguna de estas librerias.

Para comenzar hagamos un pequeño Addon el cual hará lo siguiente in C++:

exports.hello = 'world';

Para comenzar creamos el fichero hello.cc :

#include <v8.h>

using namespace v8;

extern "C" void


init (Handle<Object> target)
{
HandleScope scope;
target->Set(String::New("hello"), String::New("world"));
}

Este código fuente necesita ser construido dentro de hello.node , el Addon binario. Para hacer esto nosotros
creamos un fichero llamado wscript el cual es código python y se ve como sigue:

srcdir = '.'
blddir = 'build'
VERSION = '0.0.1'

def set_options(opt):
opt.tool_options('compiler_cxx')

def configure(conf):
conf.check_tool('compiler_cxx')
conf.check_tool('node_addon')

def build(bld):
obj = bld.new_task_gen('cxx', 'shlib', 'node_addon')

http://nodejs-es.github.io/api/all.html 21/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación
obj.target = 'hello'
obj.source = 'hello.cc'

Lanzando node-waf configure build crearemos un fichero build/default/hello.node el cual es


nuestro Addon.

node-waf es solo WAF, el sistema de construcción basado en python. node-waf is proporcionado para la
facilidad de los usuarios.

Todos los Addons de Node deben exportar un función llamada init con la siguiente constitución:

extern 'C' void init (Handle<Object> target)

Por el momento, esta es toda la documentación sobre Addons. Por favor, mira
https://github.com/ry/node_postgres para un ejemplo real.

process #
El objeto process es un objeto global y puede ser accedido desde cualquier parte. Es una instancia de
EventEmitter .

Evento: 'exit' #
function () {}

Emitido cuando el proceso está apunto de salir. Es un buen hook para realizar un control del tiempo constante
del estado del módulo (por ejemplo para tests unitarios).
El bucle del evento principal no seguirá ejecutándose después de finalizar el callback 'exit', por lo tanto los timers
no pueden ser programados.

Ejemplo escuchando a exit :

process.on('exit', function () {
process.nextTick(function () {
console.log('Esto no se ejecutará');
});
console.log('Apunto de salir.');
});

Evento: 'uncaughtException' #
function (err) { }

Emitido cuando una excepción es devuelta hacia el bucle de evento. Si se ha añadido un listener a esta excepción,
no se producirá la acción por defecto (imprimir una traza del stack y salir).

Ejemplo escuchando a uncaughtException :

process.on('uncaughtException', function (err) {


console.log('Excepción recogida: ' + err);
});

http://nodejs-es.github.io/api/all.html 22/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación
setTimeout(function () {
console.log('Esto seguirá ejecutándose.');
}, 500);

// Se fuerza una excepción, pero no se recoge.


nonexistentFunc();
console.log('Esto no se ejecutará.');

Nótese que uncaughtException es un mecanismo muy básico para manejar excepciones. Usando try / catch en
tu programa te dará más control sobre el flujo de tu programa. Especialmente para aplicaciones de servidor que
están diseñados para ejecutarse eternamente, uncaughtException puede ser un mecanismo muy útil de
seguridad.

Eventos de señal #
function () {}

Emitido cuando los procesos reciben una señal. Mirar sigaction(2) para una lista de nombres de señal estándard
POSIX como SIGINT, SIGUSR1, etc.

Ejemplo escuchando a SIGINT :

// Empieza leyendo de stdin para evitar salir.


process.stdin.resume();

process.on('SIGINT', function () {
console.log('Recibido SIGINT. Haz Control-D para salir.');
});

Una manera sencilla de enviar la señal SIGINT es con Control-C en la mayoria de aplicaciones de terminal.

process.stdout #
Un Stream de Escritura para stdout .

Ejemplo: la definición de console.log

console.log = function (d) {


process.stdout.write(d + '\n');
};

process.stderr #
Un stream de escritura para stderr. Las escrituras en este stream son bloqueantes.

process.stdin #
Un Stream de Lectura para stdin. El stream stdin se detiene por defecto, así que se tiene que llamar a
process.stdin.resume() para leer de él.

Ejemplo de como abir la entrada estándard (stdin) y escuchar a ambos eventos:

http://nodejs-es.github.io/api/all.html 23/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

process.stdin.resume();
process.stdin.setEncoding('utf8');

process.stdin.on('data', function (chunk) {


process.stdout.write('data: ' + chunk);
});

process.stdin.on('end', function () {
process.stdout.write('end');
});

process.argv #
Un array que contiene los argumentos de la línea de comandos. El primer elemento será 'node', el segundo
elemento será el nombre del fichero JavaScript. Los siguientes elementos serán argumentos adicionales de la
línea de comandos.

// imprimir process.argv
process.argv.forEach(function (val, index, array) {
console.log(index + ': ' + val);
});

Generará:

$ node process-2.js one two=three four


0: node
1: /Users/mjr/work/node/process-2.js
2: one
3: two=three
4: four

process.execPath #
Es la ruta absoluta del ejecutable que inició el proceso.

Ejemplo:

/usr/local/bin/node

process.chdir(directory) #
Cambia el directorio actual de trabajo del proceso o lanza una excepción si falla.

console.log('Directorio inicial: ' + process.cwd());


try {
process.chdir('/tmp');
console.log('Directorio nuevo: ' + process.cwd());
}
catch (err) {
console.log('chdir: ' + err);
}

http://nodejs-es.github.io/api/all.html 24/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

process.cwd() #
Devuelve el directorio actual de trabajo del proceso.

console.log('Directorio actual: ' + process.cwd());

process.env #
Un objeto que contiene el entorno del usuario. Mirar environ(7).

process.exit(code=0) #
Termina el proceso con el code especificado. Si se omite, exit usa el código de 'éxito' 0 .

Para salir con un código de 'fallo':

process.exit(1);

El shell que ha ejecutado node debería ver 1 como código de salida.

process.getgid() #
Obtiene la identidad de grupo del proceso. (Mirar getgid(2).) Es el id de grupo numérico, no el nombre del grupo.

console.log('Actual gid: ' + process.getgid());

process.setgid(id) #
Establece la identidad de grupo del proceso. (Mirar setgid(2).) Acepta tanto un ID numérico como una cadena de
texto con el nombre del grupo. Si se especifica el nombre del grupo, el método se bloquea mientras lo resuelve a
un ID numérico.

console.log('Actual gid: ' + process.getgid());


try {
process.setgid(501);
console.log('Nuevo gid: ' + process.getgid());
}
catch (err) {
console.log('Fallo al cambiar el gid: ' + err);
}

process.getuid() #
Obtiene la identidad de usuario del proceso. (Mirar getuid(2).) Es la id de usuario númerica, no el nombre de
usuario.

console.log('Actual uid: ' + process.getuid());

http://nodejs-es.github.io/api/all.html 25/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

process.setuid(id) #
Establece la identidad de usuario del proceso. (Mirar setuid(2).) Acepta tanto un ID numérico como una cadena
de texto con el nombre de usuario. Si se especifica el nombre de usuario, el método se bloquea mientras lo
resuelve a un ID numérico.

console.log('Actual uid: ' + process.getuid());


try {
process.setuid(501);
console.log('Nuevo uid: ' + process.getuid());
}
catch (err) {
console.log('Fallo al establecer uid: ' + err);
}

process.version #
Una propiedad dentro del compilado que expone NODE_VERSION .

console.log('Versión: ' + process.version);

process.installPrefix #
Una propiedad dentro del compilado que expone NODE_PREFIX .

console.log('Prefijo: ' + process.installPrefix);

process.kill(pid, signal='SIGTERM') #
Envia una señal a un proceso. pid es la id de proceso y signal es la cadena de texto que describe la señal a
enviar. Los nombres de señales son cadenas de texto como 'SIGINT' o 'SIGUSR1'. Si se omite, la señal será
'SIGTERM'. Mirar kill(2) para más información.

Notar que ya que el nombre de la función es process.kill , se trata solo de un emisor de señales, como la
llamada a sistema kill . La señal enviada puede hacer algo más que matar el proceso escogido.

Ejemplo de como enviarse una señal a uno mismo:

process.on('SIGHUP', function () {
console.log('Recibida señal SIGHUP.');
});

setTimeout(function () {
console.log('Saliendo.');
process.exit(0);
}, 100);

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

http://nodejs-es.github.io/api/all.html 26/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

process.pid #
El PID del proceso.

console.log('El pid de este proceso es ' + process.pid);

process.title #
Getter/setter para establecer lo que mostrará 'ps'.

process.platform #
En que plataforma se está ejecutando. 'linux2' , 'darwin' , etc.

console.log('La plataforma es ' + process.platform);

process.memoryUsage() #
Devuelve un objeto describiendo el uso de la memoria del proceso Node.

var util = require('util');

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

Generará:

{ rss: 4935680,
vsize: 41893888,
heapTotal: 1826816,
heapUsed: 650472 }

heapTotal y heapUsed se refieren al uso de la memoria de V8.

process.nextTick(callback) #
En la siguiente iteración del bucle del evento se llama a callback. No es simplemente un alias para
setTimeout(fn, 0) , es mucho más eficiente.

process.nextTick(function () {
console.log('nextTick callback');
});

process.umask([mask]) #
Establece o lee la máscara del modo de creación del fichero del proceso. Los procesos hijos heredan la máscara
del proceso padre. Devuelve la antigua máscara si se pasa el argumento mask , si no devuelve la máscara actual.

var oldmask, newmask = 0644;


http://nodejs-es.github.io/api/all.html 27/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

oldmask = process.umask(newmask);
console.log('Cambiada umask de: ' + oldmask.toString(8) +
' a ' + newmask.toString(8));

util #

Stability: 5 - Locked

Estas funciones estan en el módulo 'util' . Usa require('util') para acceder a ellas.

util.format() #
Returns a formatted string using the first argument as a printf -like format.

The first argument is a string that contains zero or more placeholders. Each placeholder is replaced with the
converted value from its corresponding argument. Supported placeholders are:

%s - String.
%d - Number (both integer and float).
%j - JSON.
%% - single percent sign ('%'). This does not consume an argument.

If the placeholder does not have a corresponding argument, the placeholder is not replaced.

util.format('%s:%s', 'foo'); // 'foo:%s'

If there are more arguments than placeholders, the extra arguments are converted to strings with
util.inspect() and these strings are concatenated, delimited by a space.

util.format('%s:%s', 'foo', 'bar', 'baz'); // 'foo:bar baz'

If the first argument is not a format string then util.format() returns a string that is the concatenation of all
its arguments separated by spaces. Each argument is converted to a string with util.inspect() .

util.format(1, 2, 3); // '1 2 3'

util.debug(string) #
Una función de salida síncrona. Bloquerá el proceso y pondrá string inmediatamente en stderr .

require('util').debug('mensaje en stderr');

util.log(string) #
Salida con timestamp en stdout .

require('util').log('Mensaje con marca de tiempo.');

http://nodejs-es.github.io/api/all.html 28/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

util.inspect(object, showHidden=false, depth=2) #


Devuelve la cadena que representa a object , lo cual es útil para corregir fallos.

Si showHidden es true , entonces las propiedades no-enumerables del objeto serán mostradas también. Por
omisión es false .

Si depth es proporcionado, le dice a inspect cuantas veces tiene que recurrir mientras formatea el objeto.
Esto es útil para objetos muy largos y complejos.

Por defecto solo se recurre un par de veces. Para hacer que recurra indefinidamente pasa null a depth .

Si colors es true , entonces la salida mostrará los estilos con los código de colores en ANSI. Por omisión es
false .

Ejemplo de inspeccionar todas las propiedades del objeto util :

var util = require('util');

console.log(util.inspect(util, true, null));

util.isArray(object) #
Returns true if the given "object" is an Array . false otherwise.

var util = require('util');

util.isArray([])
// true
util.isArray(new Array)
// true
util.isArray({})
// false

util.isRegExp(object) #
Returns true if the given "object" is a RegExp . false otherwise.

var util = require('util');

util.isRegExp(/some regexp/)
// true
util.isRegExp(new RegExp('another regexp'))
// true
util.isRegExp({})
// false

util.isDate(object) #
Returns true if the given "object" is a Date . false otherwise.

http://nodejs-es.github.io/api/all.html 29/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

var util = require('util');

util.isDate(new Date())
// true
util.isDate(Date())
// false (without 'new' returns a String)
util.isDate({})
// false

util.isError(object) #
Returns true if the given "object" is an Error . false otherwise.

var util = require('util');

util.isError(new Error())
// true
util.isError(new TypeError())
// true
util.isError({ name: 'Error', message: 'an error occurred' })
// false

util.pump(readableStream, writableStream, [callback]) #


Experimental

Lee los datos desde readableStream y los envia al writableStream . Cuando


writableStream.write(data) devuelve false readableStream será pausado hasta que ocurra el evento
drain sobre writableStream . callback tiene un error como único argumento y es llamada cuando
writableStream es cerrado o cuando ocurre un error.

util.inherits(constructor, superConstructor) #
Hereda los métodos del prototype desde un constructor dentro de otro. El prototype del constructor será
configurado a un nuevo objecto creado desde superConstructor .

Como mejora adicional, superConstructor será accesible atravez de la propiedad constructor.super_ .

var util = require("util");


var events = require("events");

function MyStream() {
events.EventEmitter.call(this);
}

util.inherits(MyStream, events.EventEmitter);

MyStream.prototype.write = function(data) {
this.emit("data", data);
}

var stream = new MyStream();

console.log(stream instanceof events.EventEmitter); // true

http://nodejs-es.github.io/api/all.html 30/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación
console.log(MyStream.super_ === events.EventEmitter); // true

stream.on("data", function(data) {
console.log('Received data: "' + data + '"');
})
stream.write("It works!"); // Received data: "It works!"

Eventos #
Muchos objetos en Node emiten eventos: un net.Server emite un evento cada vez que se establece una
conexión, un fs.readStream emite un evento cuando se abre un fichero. Todos los objectos que emiten
eventos son instancias de events.EventEmitter . Puedes usar este módulo haciendo require("events");

Normalmente, los nombres de los eventos siguen la notacion camel-case, sin embargo, no hay ninguna
restricción en este aspecto y cualquier cadena será aceptada.

Se pueden adjuntar funciones a objetos, para que sean ejecutadas cuando se emita un evento. Estas funciones
reciben el nombre de listeners.

events.EventEmitter #
Para usar la clase EventEmitter, haz de importarla haciendo require('events').EventEmiter .

Cuando una instancia de la clase EventEmitter se encuentra con un error, la acción típica es emitir un evento de
error. Los eventos de error son tratados como un caso especial en node. Si no tiene un listener asociado la acción
por defecto será imprimir la traza de la pila y salir del programa

Todos los EventEmitters emite el evento 'newListener' cuando se añaden nuevos listeners.

emitter.addListener(event, listener) #

emitter.on(event, listener) #
Añade un listener al final del array de listeners para el evento espeficicado

server.on('connection', function (stream) {


console.log('someone connected!');
});

emitter.once(event, listener) #
Añade un listener al evento. El listener se invocará sólo la primera vez que se dispara el evento. luego se elimina.

server.once('connection', function (stream) {


console.log('Ah, we have our first user!');
});

emitter.removeListener(event, listener) #
Elimina un listener del array de listeners asociado al evento especificado Atención: modifica el indice del array
de listeners

http://nodejs-es.github.io/api/all.html 31/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

var callback = function(stream) {


console.log('someone connected!');
};
server.on('connection', callback);
// ...
server.removeListener('connection', callback);

emitter.removeAllListeners(event) #
Elimina todos los listeners del array de listeners asociado al evento especificado

emitter.setMaxListeners(n) #
Por defecto los EventEmitters imprimirán un warning si se le añaden más de 10 listeners. Este comportamiento
por defecto ayuda a encontrar memory leaks. Obviamente no todos los EventEmitters deberían limitarse a 10.
Esta función permite incrementar este valor. Use cero para establecer un valor ilimitado.

emitter.listeners(event) #
Devuelve un array de listeners asociado al evento especificado. Este array puede ser manipulado, por ejemplo,
eliminando un listener.

server.on('connection', function (stream) {


console.log('someone connected!');
});
console.log(util.inspect(server.listeners('connection')); // [ [Function] ]

emitter.emit(event, [arg1], [arg2], [...]) #


Llama a cada uno de los listeners en el orden en el que fueron pasados por parámetros

Event: 'newListener' #
function (event, listener) { }

Este evento es emitido cada vez que se añade un nuevo listener.

Buffer #

Stability: 3 - Stable

El puro Javascript es amigable con Unicode, pero no se lleva tan bien con los datos binarios. Cuando tratamos
con streams TCP o ficheros del sistema, es necesario manejar streams de octets. Node tiene algunas estrategias
para manipular, crear, y consumir streams de octets.

Los datos en Raw son almacenados en instancias de la clase Buffer . Un Buffer es similar a un array de
integers pero correspondiendo a una localización en raw de la memeria fuera del heap de V8. Un Buffer no
puede ser redimencionado.

La clase Buffer es global, dado que es muy raro hacer un require('buffer') .


http://nodejs-es.github.io/api/all.html 32/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

Convertir entre Buffers y objectos String de Javascript requiere de un método de codificación explícito. Aquí
están las diferentes cadenas de codificación.

'ascii' - solo para datos de 7 bit ASCII. Este método de codificación es muy rápido y dejará el bit alto si
está configurado. Note that this encoding converts a null character ( '\0' or '\u0000' ) into 0x20
(character code of a space). If you want to convert a null character into 0x00 , you should use 'utf8' .
'utf8' - Multiples bytes de caracteres con codificación Unicode. Muchas páginas webs y otros formatos
de documentos usan UTF-8.
'ucs2' - 2-bytes, de caracteres con codificación little endian Unicode. Sólo pueden codificar
BMP(Basic Multilingual Plane, U+0000 - U+FFFF).
'base64' - String codificado a Base64.
'binary' - Una forma de codificar datos binarios en Raw dentro de strings pero solo usando los primeros
8 bits de cada caracter. Este método de codificación es obsoleto y debe ser evitado en favor del objeto
Buffer donde sea posible. Esta codificación será eliminada en futuras versiones de Node.
'hex' - Encode each byte as two hexidecimal characters.

Class: Buffer #
The Buffer class is a global type for dealing with binary data directly. It can be constructed in a variety of ways.

new Buffer(size) #
size Number

Asigna un nuevo buffer de size octets.

new Buffer(array) #
array Array

Asigna un nuevo buffer usando un array de octets.

new Buffer(str, [encoding]) #


str String - string to encode.
encoding String - encoding to use, Optional.

Allocates a new buffer containing the given str . encoding defaults to 'utf8' .

buf.write(string, [offset], [length], [encoding]) #


string String - data to be written to buffer
offset Number, Optional, Default: 0
length Number, Optional
encoding String, Optional, Default: 'utf8'

Escribe string en el Buffer en offset usando el método dado. offset defaults to 0 , encoding defaults to
'utf8' . length is the number of bytes to write. Devuelve el número de octets escritos. Si Buffer no contiene
suficiente espacio para encajar en el string completo, escribirá una cantidad parcial de la cadena. length
defaults to buffer.length - offset . The method will not write partial characters.

buf = new Buffer(256);

http://nodejs-es.github.io/api/all.html 33/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

len = buf.write('\u00bd + \u00bc = \u00be', 0);


console.log(len + " bytes: " + buf.toString('utf8', 0, len));

The number of characters written (which may be different than the number of bytes written) is set in
Buffer._charsWritten and will be overwritten the next time buf.write() is called.

buf.toString([encoding], [start], [end]) #


encoding String, Optional, Default: 'utf8'
start Number, Optional, Default: 0
end Number, Optional

Decodifica y devuelve un string con los datos de un buffer codificado con encoding (por omisión en 'utf8' )
comenzando en start (por omisión 0 ) y terminando en end (por omisión buffer.length ).

Observe el ejemplo de buffer.write() , encima.

buf[index] #
Obtiene y configura el octet en index . Los valores se refieren a bytes individuales, por lo que el rango legal esta
entre 0x00 and 0xFF en hexadecimal o 0 y 255 .

Ejemplo: Copiando un cadena ASCII dentro de un buffer, un byte cada vez:

str = "node.js";
buf = new Buffer(str.length);

for (var i = 0; i < str.length ; i++) {


buf[i] = str.charCodeAt(i);
}

console.log(buf);

// node.js

Class Method: Buffer.isBuffer(obj) #


obj Object
Return: Boolean

Comprueba si obj es un Buffer .

Class Method: Buffer.byteLength(string, [encoding]) #


string String
encoding String, Optional, Default: 'utf8'
Return: Number

Da la longitud de una cadena en bytes. encoding por omisión en 'utf8' . Esto no es lo mismo como
String.prototype.length puesto que devuelve el número de caracteres en el string.

Ejemplo:

http://nodejs-es.github.io/api/all.html 34/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

str = '\u00bd + \u00bc = \u00be';

console.log(str + ": " + str.length + " characters, " +


Buffer.byteLength(str, 'utf8') + " bytes");

// ½ + ¼ = ¾: 9 characters, 12 bytes

buf.length #
Number

El tamaño del buffer en bytes. Vea que esto no es necesariamente al tamaño del contenido. length se refiere a
la cantidad de memoria asignada para el objeto buffer. No cambia cuando el contenido del buffer cambia.

buf = new Buffer(1234);

console.log(buf.length);
buf.write("some string", "ascii", 0);
console.log(buf.length);

// 1234
// 1234

buf.copy(targetBuffer, [targetStart], [sourceStart], [sourceEnd]) #


targetBuffer Buffer object - Buffer to copy into
targetStart Number, Optional, Default: 0
sourceStart Number, Optional, Default: 0
sourceEnd Number, Optional, Default: 0

Does copy between buffers. The source and target regions can be overlapped. targetStart and sourceStart
default to 0 . sourceEnd defaults to buffer.length .

Ejemplo: construye dos Buffers, entonces copia buf1 desde el byte 16 hasta el byte 19 dentro de buf2 ,
comenzando en el octavo byte de buf2 .

buf1 = new Buffer(26);


buf2 = new Buffer(26);

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


buf1[i] = i + 97; // 97 is ASCII a
buf2[i] = 33; // ASCII !
}

buf1.copy(buf2, 8, 16, 20);


console.log(buf2.toString('ascii', 0, 25));

// !!!!!!!!qrst!!!!!!!!!!!!!

buf.slice([start], [end]) #
start Number, Optional, Default: 0
http://nodejs-es.github.io/api/all.html 35/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

end Number, Optional, Default: 0

Devuelve un nuevo buffer el cual hace referencia a la misma memoria que el antíguo, pero desplazado y cortado
por los indices start (por omisión 0 ) and end (por omisión buffer.length ).

¡Al modificar el nuevo buffer, modificarás la memoria en el buffer original!

Ejemplo: contruye un Buffer con el alfabeto ASCII, toma un fragmento, y entonces modifica un byte desde el
Buffer original.

var buf1 = new Buffer(26);

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


buf1[i] = i + 97; // 97 is ASCII a
}

var buf2 = buf1.slice(0, 3);


console.log(buf2.toString('ascii', 0, buf2.length));
buf1[0] = 33;
console.log(buf2.toString('ascii', 0, buf2.length));

// abc
// !bc

buf.readUInt8(offset, [noAssert]) #
offset Number
noAssert Boolean, Optional, Default: false
Return: Number

Reads an unsigned 8 bit integer from the buffer at the specified offset.

Set noAssert to true to skip validation of offset . This means that offset may be beyond the end of the
buffer. Defaults to false .

Example:

var buf = new Buffer(4);

buf[0] = 0x3;
buf[1] = 0x4;
buf[2] = 0x23;
buf[3] = 0x42;

for (ii = 0; ii < buf.length; ii++) {


console.log(buf.readUInt8(ii));
}

// 0x3
// 0x4
// 0x23
// 0x42

buf.readUInt16LE(offset, [noAssert]) #
http://nodejs-es.github.io/api/all.html 36/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

buf.readUInt16BE(offset, [noAssert]) #
offset Number
noAssert Boolean, Optional, Default: false
Return: Number

Reads an unsigned 16 bit integer from the buffer at the specified offset with specified endian format.

Set noAssert to true to skip validation of offset . This means that offset may be beyond the end of the
buffer. Defaults to false .

Example:

var buf = new Buffer(4);

buf[0] = 0x3;
buf[1] = 0x4;
buf[2] = 0x23;
buf[3] = 0x42;

console.log(buf.readUInt16BE(0));
console.log(buf.readUInt16LE(0));
console.log(buf.readUInt16BE(1));
console.log(buf.readUInt16LE(1));
console.log(buf.readUInt16BE(2));
console.log(buf.readUInt16LE(2));

// 0x0304
// 0x0403
// 0x0423
// 0x2304
// 0x2342
// 0x4223

buf.readUInt32LE(offset, [noAssert]) #
buf.readUInt32BE(offset, [noAssert]) #
offset Number
noAssert Boolean, Optional, Default: false
Return: Number

Reads an unsigned 32 bit integer from the buffer at the specified offset with specified endian format.

Set noAssert to true to skip validation of offset . This means that offset may be beyond the end of the
buffer. Defaults to false .

Example:

var buf = new Buffer(4);

buf[0] = 0x3;
buf[1] = 0x4;
buf[2] = 0x23;
buf[3] = 0x42;

http://nodejs-es.github.io/api/all.html 37/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

console.log(buf.readUInt32BE(0));
console.log(buf.readUInt32LE(0));

// 0x03042342
// 0x42230403

buf.readInt8(offset, [noAssert]) #
offset Number
noAssert Boolean, Optional, Default: false
Return: Number

Reads a signed 8 bit integer from the buffer at the specified offset.

Set noAssert to true to skip validation of offset . This means that offset may be beyond the end of the
buffer. Defaults to false .

Works as buffer.readUInt8 , except buffer contents are treated as two's complement signed values.

buf.readInt16LE(offset, [noAssert]) #
buf.readInt16BE(offset, [noAssert]) #
offset Number
noAssert Boolean, Optional, Default: false
Return: Number

Reads a signed 16 bit integer from the buffer at the specified offset with specified endian format.

Set noAssert to true to skip validation of offset . This means that offset may be beyond the end of the
buffer. Defaults to false .

Works as buffer.readUInt16* , except buffer contents are treated as two's complement signed values.

buf.readInt32LE(offset, [noAssert]) #
buf.readInt32BE(offset, [noAssert]) #
offset Number
noAssert Boolean, Optional, Default: false
Return: Number

Reads a signed 32 bit integer from the buffer at the specified offset with specified endian format.

Set noAssert to true to skip validation of offset . This means that offset may be beyond the end of the
buffer. Defaults to false .

Works as buffer.readUInt32* , except buffer contents are treated as two's complement signed values.

buf.readFloatLE(offset, [noAssert]) #
buf.readFloatBE(offset, [noAssert]) #

http://nodejs-es.github.io/api/all.html 38/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

offset Number
noAssert Boolean, Optional, Default: false
Return: Number

Reads a 32 bit float from the buffer at the specified offset with specified endian format.

Set noAssert to true to skip validation of offset . This means that offset may be beyond the end of the
buffer. Defaults to false .

Example:

var buf = new Buffer(4);

buf[0] = 0x00;
buf[1] = 0x00;
buf[2] = 0x80;
buf[3] = 0x3f;

console.log(buf.readFloatLE(0));

// 0x01

buf.readDoubleLE(offset, [noAssert]) #
buf.readDoubleBE(offset, [noAssert]) #
offset Number
noAssert Boolean, Optional, Default: false
Return: Number

Reads a 64 bit double from the buffer at the specified offset with specified endian format.

Set noAssert to true to skip validation of offset . This means that offset may be beyond the end of the
buffer. Defaults to false .

Example:

var buf = new Buffer(8);

buf[0] = 0x55;
buf[1] = 0x55;
buf[2] = 0x55;
buf[3] = 0x55;
buf[4] = 0x55;
buf[5] = 0x55;
buf[6] = 0xd5;
buf[7] = 0x3f;

console.log(buf.readDoubleLE(0));

// 0.3333333333333333

buf.writeUInt8(value, offset, [noAssert]) #

http://nodejs-es.github.io/api/all.html 39/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

value Number
offset Number
noAssert Boolean, Optional, Default: false

Writes value to the buffer at the specified offset. Note, value must be a valid unsigned 8 bit integer.

Set noAssert to true to skip validation of value and offset . This means that value may be too large for
the specific function and offset may be beyond the end of the buffer leading to the values being silently
dropped. This should not be used unless you are certain of correctness. Defaults to false .

Example:

var buf = new Buffer(4);


buf.writeUInt8(0x3, 0);
buf.writeUInt8(0x4, 1);
buf.writeUInt8(0x23, 2);
buf.writeUInt8(0x42, 3);

console.log(buf);

// <Buffer 03 04 23 42>

buf.writeUInt16LE(value, offset, [noAssert]) #


buf.writeUInt16BE(value, offset, [noAssert]) #
value Number
offset Number
noAssert Boolean, Optional, Default: false

Writes value to the buffer at the specified offset with specified endian format. Note, value must be a valid
unsigned 16 bit integer.

Set noAssert to true to skip validation of value and offset . This means that value may be too large for
the specific function and offset may be beyond the end of the buffer leading to the values being silently
dropped. This should not be used unless you are certain of correctness. Defaults to false .

Example:

var buf = new Buffer(4);


buf.writeUInt16BE(0xdead, 0);
buf.writeUInt16BE(0xbeef, 2);

console.log(buf);

buf.writeUInt16LE(0xdead, 0);
buf.writeUInt16LE(0xbeef, 2);

console.log(buf);

// <Buffer de ad be ef>
// <Buffer ad de ef be>

buf.writeUInt32LE(value, offset, [noAssert]) #


http://nodejs-es.github.io/api/all.html 40/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

buf.writeUInt32BE(value, offset, [noAssert]) #


value Number
offset Number
noAssert Boolean, Optional, Default: false

Writes value to the buffer at the specified offset with specified endian format. Note, value must be a valid
unsigned 32 bit integer.

Set noAssert to true to skip validation of value and offset . This means that value may be too large for
the specific function and offset may be beyond the end of the buffer leading to the values being silently
dropped. This should not be used unless you are certain of correctness. Defaults to false .

Example:

var buf = new Buffer(4);


buf.writeUInt32BE(0xfeedface, 0);

console.log(buf);

buf.writeUInt32LE(0xfeedface, 0);

console.log(buf);

// <Buffer fe ed fa ce>
// <Buffer ce fa ed fe>

buf.writeInt8(value, offset, [noAssert]) #


value Number
offset Number
noAssert Boolean, Optional, Default: false

Writes value to the buffer at the specified offset. Note, value must be a valid signed 8 bit integer.

Set noAssert to true to skip validation of value and offset . This means that value may be too large for
the specific function and offset may be beyond the end of the buffer leading to the values being silently
dropped. This should not be used unless you are certain of correctness. Defaults to false .

Works as buffer.writeUInt8 , except value is written out as a two's complement signed integer into buffer .

buf.writeInt16LE(value, offset, [noAssert]) #


buf.writeInt16BE(value, offset, [noAssert]) #
value Number
offset Number
noAssert Boolean, Optional, Default: false

Writes value to the buffer at the specified offset with specified endian format. Note, value must be a valid
signed 16 bit integer.

Set noAssert to true to skip validation of value and offset . This means that value may be too large for
the specific function and offset may be beyond the end of the buffer leading to the values being silently
dropped. This should not be used unless you are certain of correctness. Defaults to false .

http://nodejs-es.github.io/api/all.html 41/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

Works as buffer.writeUInt16* , except value is written out as a two's complement signed integer into
buffer .

buf.writeInt32LE(value, offset, [noAssert]) #


buf.writeInt32BE(value, offset, [noAssert]) #
value Number
offset Number
noAssert Boolean, Optional, Default: false

Writes value to the buffer at the specified offset with specified endian format. Note, value must be a valid
signed 32 bit integer.

Set noAssert to true to skip validation of value and offset . This means that value may be too large for
the specific function and offset may be beyond the end of the buffer leading to the values being silently
dropped. This should not be used unless you are certain of correctness. Defaults to false .

Works as buffer.writeUInt32* , except value is written out as a two's complement signed integer into
buffer .

buf.writeFloatLE(value, offset, [noAssert]) #


buf.writeFloatBE(value, offset, [noAssert]) #
value Number
offset Number
noAssert Boolean, Optional, Default: false

Writes value to the buffer at the specified offset with specified endian format. Note, value must be a valid 32
bit float.

Set noAssert to true to skip validation of value and offset . This means that value may be too large for
the specific function and offset may be beyond the end of the buffer leading to the values being silently
dropped. This should not be used unless you are certain of correctness. Defaults to false .

Example:

var buf = new Buffer(4);


buf.writeFloatBE(0xcafebabe, 0);

console.log(buf);

buf.writeFloatLE(0xcafebabe, 0);

console.log(buf);

// <Buffer 4f 4a fe bb>
// <Buffer bb fe 4a 4f>

buf.writeDoubleLE(value, offset, [noAssert]) #


buf.writeDoubleBE(value, offset, [noAssert]) #

http://nodejs-es.github.io/api/all.html 42/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

value Number
offset Number
noAssert Boolean, Optional, Default: false

Writes value to the buffer at the specified offset with specified endian format. Note, value must be a valid 64
bit double.

Set noAssert to true to skip validation of value and offset . This means that value may be too large for
the specific function and offset may be beyond the end of the buffer leading to the values being silently
dropped. This should not be used unless you are certain of correctness. Defaults to false .

Example:

var buf = new Buffer(8);


buf.writeDoubleBE(0xdeadbeefcafebabe, 0);

console.log(buf);

buf.writeDoubleLE(0xdeadbeefcafebabe, 0);

console.log(buf);

// <Buffer 43 eb d5 b7 dd f9 5f d7>
// <Buffer d7 5f f9 dd b7 d5 eb 43>

buf.fill(value, [offset], [end]) #


value
offset Number, Optional
end Number, Optional

Fills the buffer with the specified value. If the offset (defaults to 0 ) and end (defaults to buffer.length )
are not given it will fill the entire buffer.

var b = new Buffer(50);


b.fill("h");

buffer.INSPECT_MAX_BYTES #
Number, Default: 50

How many bytes will be returned when buffer.inspect() is called. This can be overridden by user modules.

Note that this is a property on the buffer module returned by require('buffer') , not on the Buffer global, or
a buffer instance.

Class: SlowBuffer #
This class is primarily for internal use. JavaScript programs should use Buffer instead of using SlowBuffer.

In order to avoid the overhead of allocating many C++ Buffer objects for small blocks of memory in the lifetime
of a server, Node allocates memory in 8Kb (8192 byte) chunks. If a buffer is smaller than this size, then it will be
backed by a parent SlowBuffer object. If it is larger than this, then Node will allocate a SlowBuffer slab for it
directly.
http://nodejs-es.github.io/api/all.html 43/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

Streams #
Un Stream es un interfaz abstracto implementado por varios objetos en Node. Por ejemplo una petición a un
servidor HTTP es un Stream, como un stdout. Los Streams son legibles, escribibles o ambos. Todos los stream
son instancias de EventEmitter .

Readable Stream #
A Readable Stream has the following methods, members, and events.

Event: 'data' #
function (data) { }

The 'data' event emits either a Buffer (by default) or a string if setEncoding() was used.

Event: 'end' #
function () { }

Emitted when the stream has received an EOF (FIN in TCP terminology). Indicates that no more 'data' events
will happen. If the stream is also writable, it may be possible to continue writing.

Event: 'error' #
function (exception) { }

Emitted if there was an error receiving data.

Event: 'close' #
function () { }

Emitted when the underlying file descriptor has been closed. Not all streams will emit this. (For example, an
incoming HTTP request will not emit 'close' .)

Event: 'fd' #
function (fd) { }

Emitted when a file descriptor is received on the stream. Only UNIX streams support this functionality; all others
will simply never emit this event.

stream.readable #
A boolean that is true by default, but turns false after an 'error' occurred, the stream came to an 'end' ,
or destroy() was called.

http://nodejs-es.github.io/api/all.html 44/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

stream.setEncoding(encoding) #
Makes the data event emit a string instead of a Buffer . encoding can be 'utf8' , 'ascii' , or 'base64' .

stream.pause() #
Pauses the incoming 'data' events.

stream.resume() #
Resumes the incoming 'data' events after a pause() .

stream.destroy() #
Closes the underlying file descriptor. Stream will not emit any more events.

stream.destroySoon() #
After the write queue is drained, close the file descriptor.

stream.pipe(destination, [options]) #
This is a Stream.prototype method available on all Stream s.

Connects this read stream to destination WriteStream. Incoming data on this stream gets written to
destination . The destination and source streams are kept in sync by pausing and resuming as necessary.

Emulating the Unix cat command:

process.stdin.resume();
process.stdin.pipe(process.stdout);

By default end() is called on the destination when the source stream emits end , so that destination is no
longer writable. Pass { end: false } as options to keep the destination stream open.

This keeps process.stdout open so that "Goodbye" can be written at the end.

process.stdin.resume();

process.stdin.pipe(process.stdout, { end: false });

process.stdin.on("end", function() {
process.stdout.write("Goodbye\n");
});

NOTE: If the source stream does not support pause() and resume() , this function adds simple definitions
which simply emit 'pause' and 'resume' events on the source stream.

Writable Stream #

http://nodejs-es.github.io/api/all.html 45/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

A Writable Stream has the following methods, members, and events.

Event: 'drain' #
function () { }

Emitted after a write() method was called that returned false to indicate that it is safe to write again.

Event: 'error' #
function (exception) { }

Emitted on error with the exception exception .

Event: 'close' #
function () { }

Emitted when the underlying file descriptor has been closed.

Event: 'pipe' #
function (src) { }

Emitted when the stream is passed to a readable stream's pipe method.

stream.writable #
A boolean that is true by default, but turns false after an 'error' occurred or end() / destroy() was
called.

stream.write(string, encoding='utf8', [fd]) #


Writes string with the given encoding to the stream. Returns true if the string has been flushed to the
kernel buffer. Returns false to indicate that the kernel buffer is full, and the data will be sent out in the future.
The 'drain' event will indicate when the kernel buffer is empty again. The encoding defaults to 'utf8' .

If the optional fd parameter is specified, it is interpreted as an integral file descriptor to be sent over the stream.
This is only supported for UNIX streams, and is silently ignored otherwise. When writing a file descriptor in this
manner, closing the descriptor before the stream drains risks sending an invalid (closed) FD.

stream.write(buffer) #
Same as the above except with a raw buffer.

stream.end() #
Terminates the stream with EOF or FIN.

http://nodejs-es.github.io/api/all.html 46/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

stream.end(string, encoding) #
Sends string with the given encoding and terminates the stream with EOF or FIN. This is useful to reduce
the number of packets sent.

stream.end(buffer) #
Same as above but with a buffer .

stream.destroy() #
Closes the underlying file descriptor. Stream will not emit any more events.

stream.destroySoon() #
After the write queue is drained, close the file descriptor. destroySoon() can still destroy straight away, as long
as there is no data left in the queue for writes.

Crypto #

Stability: 3 - Stable

Usa require('crypto') para acceder a este módulo.

El módulo crypto necesita que OpenSSL esté disponible en el sistema. Ofrece una forma de encapsular
credenciales seguras para ser usadas como parte de una red HTTPS segura o una conexión http.

Además ofrece un conjunto de envoltorios para los métodos hash, hmac, cipher, decipher, sign y verify de
OpenSSL.

crypto.createCredentials(details) #
Crea un objeto credenciales, con los detalles opcionales en forma de diccionario con las siguientes claves:

key : cadena que contiene la clave privada codificada en PEM.


passphrase : A string of passphrase for the private key
cert : cadena que contiene el certificado codificado en PEM.
ca : cadena o lista de cadenas de certificados de confianza codificados en PEM.
crl : Either a string or list of strings of PEM encoded CRLs (Certificate Revocation List)
ciphers: A string describing the ciphers to use or exclude. Consult
http://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT for details on the format.

Si no se han dado ningún elemento en ca , node.js usará la lista de CAs de confianza publicadas como dice en

http://mxr.mozilla.org/mozilla/source/security/nss/lib/ckfw/builtins/certdata.txt.

crypto.createHash(algorithm) #
Crea y devuelve un nuevo objeto hash, un hash criptográfico con el algoritmo dado que puede ser usado para
generar el hash digests.

http://nodejs-es.github.io/api/all.html 47/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

algorithm depende de los algoritmos disponibles en la versión de OpenSSL en el sistema. Algunos ejemplos
son 'sha1' , 'md5' , 'sha256' , 'sha512' , etc. En versiones recientes, openssl list-message-digest-
algorithms mostrará los algoritmos digest disponibles.

Example: this program that takes the sha1 sum of a file

var filename = process.argv[2];


var crypto = require('crypto');
var fs = require('fs');

var shasum = crypto.createHash('sha1');

var s = fs.ReadStream(filename);
s.on('data', function(d) {
shasum.update(d);
});

s.on('end', function() {
var d = shasum.digest('hex');
console.log(d + ' ' + filename);
});

Class: Hash #
The class for creating hash digests of data.

Returned by crypto.createHash .

hash.update(data) #
Actualiza el contenido del hash con el data dado. the encoding of which is given in input_encoding and can
be 'utf8' , 'ascii' or 'binary' . Defaults to 'binary' . Esto puede ser invocado muchas veces con dato
nuevo mientras estos van llegando.

hash.digest([encoding]) #
Calcula el digest todos los datos que van al hash. La codificación ( encoding ) puede ser 'hex' , 'binary' o
'base64' . Por omisíón es 'binary' .

Note: hash object can not be used after digest() method been called.

crypto.createHmac(algorithm, key) #
Crea y devuelve un objeto hmac, un hmac criptográfico con el algoritmo y la clave dadas.

algorithm depende de los algoritmos disponibles en la versión de OpenSSL en el sistema - ver createHash
arriba. key es la clave hmac a usar.

Class: Hmac #
Class for creating cryptographic hmac content.

http://nodejs-es.github.io/api/all.html 48/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

Returned by crypto.createHmac .

hmac.update(data) #
Actualiza el contenido del hmac con el data dado. Esto puede ser invocado muchas veces con dato nuevo
mientras estos van llegando.

hmac.digest(encoding='binary') #
Calcula el digest (resumen) de todos los datos que van al hmac. La codificación ( encoding ) puede ser 'hex' ,
'binary' o 'base64' . Por omisíón es 'binary' .

Note: hmac object can not be used after digest() method been called.

crypto.createCipher(algorithm, key) #
Crea y devuelve un objeto cipher (codificador), con el algoritmo y la clave dadas.

algorithm es dependiente de OpenSSL, por ejemplo 'aes192' , etc. En versiones recientes, openssl list-
cipher-algorithms mostrará los algoritmos cipher disponibles. password is used to derive key and IV, which
must be 'binary' encoded string (See the Buffer section for more information).

crypto.createCipheriv(algorithm, key, iv) #


Creates and returns a cipher object, with the given algorithm, key and iv.

algorithm is the same as the createCipher() . key is a raw key used in algorithm. iv is an Initialization
vector. key and iv must be 'binary' encoded string (See the Buffer section for more information).

Class: Cipher #
Class for encrypting data.

Returned by crypto.createCipher and crypto.createCipheriv .

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


Actualiza el cipher con data , la codificación viene dada en input_encoding y puede ser 'utf8' , 'ascii' o
'binary' . Por omisión 'binary' .

El output_encoding especifica el formato de la salida del dato codificado, y puede ser 'binary' , 'base64'
o 'hex' . Por omisión 'binary' .

Devuelve el contenido codificado, y puede ser llamado muchas veces a medida que nuevos datos van llegando.

cipher.final([output_encoding]) #
Devuelve cualquier contenido codificado restante, donde output_encoding puede ser: 'binary' , 'base64'
o 'hex' . Por omisión 'binary' .

http://nodejs-es.github.io/api/all.html 49/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

Note: cipher object can not be used after final() method been called.

cipher.setAutoPadding(auto_padding=true) #
You can disable automatic padding of the input data to block size. If auto_padding is false, the length of the
entire input data must be a multiple of the cipher's block size or final will fail. Useful for non-standard
padding, e.g. using 0x0 instead of PKCS padding. You must call this before cipher.final .

crypto.createDecipher(algorithm, key) #
Crea y devuelve un objeto decipher (decodificación), con el algoritmo y clave dado. Este es el simétrico del objeto
cipher (codificación) de arriba.

decipher.update(data, input_encoding='binary', #
output_encoding='binary')
Actualiza el objeto decodificador con data , que puede estar codificado en 'binary' , 'base64' o 'hex' . El
output_decoding especifica en qué formato devolver el texto plano decodificdo: 'binary' , 'ascii' o
'utf8' .

Class: Decipher #
Class for decrypting data.

Returned by crypto.createDecipher and crypto.createDecipheriv .

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


Updates the decipher with data , which is encoded in 'binary' , 'base64' or 'hex' . Defaults to
'binary' .

The output_decoding specifies in what format to return the deciphered plaintext: 'binary' , 'ascii' or
'utf8' . Defaults to 'binary' .

decipher.final([output_encoding]) #
Devuelve el texto plano decodificado restante, siendo output_encoding 'binary' , 'ascii' o 'utf8' . Por
omisión 'binary' .

Note: decipher object can not be used after final() method been called.

decipher.setAutoPadding(auto_padding=true) #
You can disable auto padding if the data has been encrypted without standard block padding to prevent
decipher.final from checking and removing it. Can only work if the input data's length is a multiple of the
ciphers block size. You must call this before streaming data to decipher.update .

crypto.createSign(algorithm) #

http://nodejs-es.github.io/api/all.html 50/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

Crea y devuelve un objeto firma (signing) con el algoritmo dado. En versiones recientes, openssl list-
public-key-algorithms muestra los algoritmos de firmado disponibles. Por ejemplo: `'RSA-SHA256

Class: Signer #
Class for generating signatures.

Returned by crypto.createSign .

signer.update(data) #
Actualiza el objeto firma con los datos dados. Puede ser llamado muchas veces a medida que nuevos datos van
llegando.

signer.sign(private_key, output_format='binary') #
Calcula la firma en todos los datos actualizados pasados a través del objetvo firma. private_key es una cadena
que contiene la clave privada para firmar codificada en PEM.

Devuelve la firma en output_format que puede estar en 'binary' , 'hex' o 'base64' . Por omisión
'binary' .

Note: signer object can not be used after sign() method been called.

crypto.createVerify(algorithm) #
Crea y devuelve un objeto verificación con el algoritmo dado. Este es el simétrico del objeto firma de arriba.

Class: Verify #
Class for verifying signatures.

Returned by crypto.createVerify .

verifier.update(data) #
Actualiza el objeto verificador con los datos dados. Puede ser llamado muchas veces a medida que nuevos datos
van llegando.

verifier.verify(cert, signature, signature_format='binary') #


Verifica los datos firmados usando cert , que es una cadena que contiene la llave pública codificada en PEM; y
signature , que es la firma del dato previamente calculada; signature_format puede ser 'binary' ,
'hex' o 'base64' .

Devuelve true o false dependiendo en la validez de la firma para el dato y la clave pública dadas.

Note: verifier object can not be used after verify() method been called.

http://nodejs-es.github.io/api/all.html 51/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

crypto.createDiffieHellman(prime_length) #
Creates a Diffie-Hellman key exchange object and generates a prime of the given bit length. The generator used is
2.

crypto.createDiffieHellman(prime, [encoding]) #
Creates a Diffie-Hellman key exchange object using the supplied prime. The generator used is 2 . Encoding can
be 'binary' , 'hex' , or 'base64' . Defaults to 'binary' .

Class: DiffieHellman #
The class for creating Diffie-Hellman key exchanges.

Returned by crypto.createDiffieHellman .

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' . Defaults
to 'binary' .

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. Supplied key is interpreted using specified input_encoding , and secret is encoded using
specified output_encoding . Encodings can be 'binary' , 'hex' , or 'base64' . The input encoding defaults
to 'binary' . If no output encoding is given, the input encoding is used as output encoding.

diffieHellman.getPrime([encoding]) #
Returns the Diffie-Hellman prime in the specified encoding, which can be 'binary' , 'hex' , or 'base64' .
Defaults to 'binary' .

diffieHellman.getGenerator([encoding]) #
Returns the Diffie-Hellman prime in the specified encoding, which can be 'binary' , 'hex' , or 'base64' .
Defaults to 'binary' .

diffieHellman.getPublicKey([encoding]) #
Returns the Diffie-Hellman public key in the specified encoding, which can be 'binary' , 'hex' , or
'base64' . Defaults to 'binary' .

diffieHellman.getPrivateKey([encoding]) #
Returns the Diffie-Hellman private key in the specified encoding, which can be 'binary' , 'hex' , or
'base64' . Defaults to 'binary' .

http://nodejs-es.github.io/api/all.html 52/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

diffieHellman.setPublicKey(public_key, [encoding]) #
Sets the Diffie-Hellman public key. Key encoding can be 'binary' , 'hex' , or 'base64' . Defaults to
'binary' .

diffieHellman.setPrivateKey(public_key, [encoding]) #
Sets the Diffie-Hellman private key. Key encoding can be 'binary' , 'hex' , or 'base64' . Defaults to
'binary' .

crypto.getDiffieHellman(group_name) #
Creates a predefined Diffie-Hellman key exchange object. The supported groups are: 'modp1' , 'modp2' ,
'modp5' (defined in RFC 2412) and 'modp14' , 'modp15' , 'modp16' , 'modp17' , 'modp18' (defined in
RFC 3526). The returned object mimics the interface of objects created by crypto.createDiffieHellman() above,
but will not allow to change the keys (with diffieHellman.setPublicKey() for example). The advantage of using
this routine is that the parties don't have to generate nor exchange group modulus beforehand, saving both
processor and communication time.

Example (obtaining a shared secret):

var crypto = require('crypto');


var alice = crypto.getDiffieHellman('modp5');
var bob = crypto.getDiffieHellman('modp5');

alice.generateKeys();
bob.generateKeys();

var alice_secret = alice.computeSecret(bob.getPublicKey(), 'binary', 'hex');


var bob_secret = bob.computeSecret(alice.getPublicKey(), 'binary', 'hex');

/* alice_secret and bob_secret should be the same */


console.log(alice_secret == bob_secret);

crypto.pbkdf2(password, salt, iterations, keylen, callback) #


Asynchronous PBKDF2 applies pseudorandom function HMAC-SHA1 to derive a key of given length from the
given password, salt and iterations. The callback gets two arguments (err, derivedKey) .

crypto.randomBytes(size, [callback]) #
Generates cryptographically strong pseudo-random data. Usage:

// async
crypto.randomBytes(256, function(ex, buf) {
if (ex) throw ex;
console.log('Have %d bytes of random data: %s', buf.length, buf);
});

// sync
try {
var buf = crypto.randomBytes(256);
console.log('Have %d bytes of random data: %s', buf.length, buf);
} catch (ex) {

http://nodejs-es.github.io/api/all.html 53/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

// handle error
}

TLS (SSL) #
Usa require('tls') para acceder a este módulo.

El módulo tls utiliza OpenSSL para proveer seguridad en la Transport Layer Security y/o Secure Socket Layer:
encriptacion de flujo de comunicaciones.

TLS/SSL es una infraestructura de clave publica/privada. Cada cliente y cada servidor deben tener una clave
privada. Una clave privada se crea como sigue:

openssl genrsa -out ryans-key.pem 1024

Todos los servidores y algunos clientes necesitan tener un certificado. Los certificados son claves públicas
firmadas por una autoridad certificadora (CA) o por ellas mismas. El primer paso para obtener un certificado es
crear un fichero de "Petición de firma de Certificado" (CSR). Esto se hace como sigue:

openssl req -new -key ryans-key.pem -out ryans-csr.pem

Para crear un certificado auto firmado con el CSR, hay que hacer:

openssl x509 -req -in ryans-csr.pem -signkey ryans-key.pem -out ryans-cert.pem

De forma alternativa puedes enviar el CSR a la autoridad certificadora para firmarlo.

(TODO: documentos sobre la creación de una CA, por ahora los usuarios interesados deberían echar un vistazo a
test/fixtures/keys/Makefile en el código fuente de Node)

s = tls.connect(port, [host], [options], callback) #


Crea una nueva conexión cliente al port y al host dados. ( host por defecto es localhost .) options debe
ser un objeto que especifique:

key : Un string o Buffer que contiene la llave privada del servidor en formato PEM. (Requerido)
cert : Un string o Buffer que contiene la clave del certificado del servidor en formato PEM.
ca : Un array de strings o Buffer s de certificados de confianza. Si esto es omitido, varias CAs "root" bien
conocidas serán usadas, como VeriSign. Estas son usadas para autorizar conexiones.

tls.connect() devuelve un objeto CryptoStream en texto plano.

Después del TSL/SSL handshake el callback es invocado. El callback será invocado independientemente si
el certificado del servidor fue autorizado o no. Es responsabilidad del usuario probar s.authorized para ver si
el certificado del servidor estaba firmado por una de las CAs especificadas. Si s.authorized === false
entonces el error puede encontrarse en s.authorizationError .

STARTTLS #
In the v0.4 branch no function exists for starting a TLS session on an already existing TCP connection. This is
possible it just requires a bit of work. The technique is to use tls.createSecurePair() which returns two

http://nodejs-es.github.io/api/all.html 54/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

streams: an encrypted stream and a plaintext stream. The encrypted stream is then piped to the socket, the
plaintext stream is what the user interacts with thereafter.

Here is some code that does it.

tls.Server #
Esta clase es una subclase de net.Server y tiene los mismos métodos. En lugar de aceptar solo conexiones TCP
en bruto, acepta conexiones encriptadas usando TLS o SSL.

Aquí hay un ejemplo simple de un servidor eco:

var tls = require('tls');


var fs = require('fs');

var options = {
key: fs.readFileSync('server-key.pem'),
cert: fs.readFileSync('server-cert.pem')
};

tls.createServer(options, function (s) {


s.write("welcome!\n");
s.pipe(s);
}).listen(8000);

Puedes probar este servidor conectándose a él con openssl s_client :

openssl s_client -connect 127.0.0.1:8000

tls.createServer(options, secureConnectionListener) #
Este es un constructor para la clase tls.Server . El objeto options puede contener:

key : Un string o Buffer que contiene la clave privada del servidor en formato PEM. (Requerido)
cert : Un string o Buffer que contiene el certificado del servidor en formato PEM. (Requerido)
ca : Un array de strings o Buffer s de certificados de confianza. Si esto es omitido, varias CAs "root" bien
conocidas serán usadas, como VeriSign. Estas son usadas para autorizar conexiones.
requestCert : Si es true el servidor solicitará un certificado de todos los clientes que se conecten e
intenten verificar ese certificado. Por defecto: false
rejectUnauthorized : Si es true el servidor rechazará cualquier conexión no autorizada por la lista de
CAs suministradas. Esta opción solo tiene efecto si requestCert es true . Por defecto: false .

Event: 'secureConnection' #
function (cleartextStream) {}

Este evento es emitido después de que una nueva conexión haya realizado con éxito el handshake. El argumento
es una instancia de stream.Stream . Tiene todos los métodos y eventos de stream.

cleartextStream.authorized es un valor boolean que indica si el cliente está verificado por una de las CA
suministradas por el servidor. Si cleartextStream.authorized es false, entonces
cleartextStream.authorizationError describe como falló la autorización. Relacionado pero merece
mencionarse: dependiendo de la configuración del servidor TLS, tus autorizaciones de conexión pueden ser
http://nodejs-es.github.io/api/all.html 55/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

aceptadas.

server.listen(port, [host], [callback]) #


Empieza aceptando conexiones en el port y el host especificados. Si el host es omitido, el servidor aceptará
conexiones dirigidas a cualquier dirección IPv4 ( INADDR_ANY ).

Esta función es asíncrona. El último parámetro callback se invocará cuando el servidor esté saturado.

Mirar net.Server para más información.

server.close() #
Detiene el servidor, dejando de aceptar conexiones. Esta función es asíncrona, el servidor finalmente se cierra
cuando emite un evento 'close' .

server.maxConnections #
Establece esta propiedad para rechazar conexiones cuando el número de conexiones del servidor sea alta.

server.connections #
Número de conexiones concurrentes en el servidor.

File System #
File I/O is provided by simple wrappers around standard POSIX functions. To use this module do
require('fs') . All the methods have asynchronous and synchronous forms.

The asynchronous form always take a completion callback as its last argument. The arguments passed to the
completion callback depend on the method, but the first argument is always reserved for an exception. If the
operation was completed successfully, then the first argument will be null or undefined .

Here is an example of the asynchronous version:

var fs = require('fs');

fs.unlink('/tmp/hello', function (err) {


if (err) throw err;
console.log('successfully deleted /tmp/hello');
});

Here is the synchronous version:

var fs = require('fs');

fs.unlinkSync('/tmp/hello')
console.log('successfully deleted /tmp/hello');

With the asynchronous methods there is no guaranteed ordering. So the following is prone to error:
http://nodejs-es.github.io/api/all.html 56/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

fs.rename('/tmp/hello', '/tmp/world', function (err) {


if (err) throw err;
console.log('renamed complete');
});
fs.stat('/tmp/world', function (err, stats) {
if (err) throw err;
console.log('stats: ' + JSON.stringify(stats));
});

It could be that fs.stat is executed before fs.rename . The correct way to do this is to chain the callbacks.

fs.rename('/tmp/hello', '/tmp/world', function (err) {


if (err) throw err;
fs.stat('/tmp/world', function (err, stats) {
if (err) throw err;
console.log('stats: ' + JSON.stringify(stats));
});
});

In busy processes, the programmer is strongly encouraged to use the asynchronous versions of these calls. The
synchronous versions will block the entire process until they complete--halting all connections.

fs.rename(path1, path2, [callback]) #


Asynchronous rename(2). No arguments other than a possible exception are given to the completion callback.

fs.renameSync(path1, path2) #
Synchronous rename(2).

fs.truncate(fd, len, [callback]) #


Asynchronous ftruncate(2). No arguments other than a possible exception are given to the completion callback.

fs.truncateSync(fd, len) #
Synchronous ftruncate(2).

fs.chmod(path, mode, [callback]) #


Asynchronous chmod(2). No arguments other than a possible exception are given to the completion callback.

fs.chmodSync(path, mode) #
Synchronous chmod(2).

fs.stat(path, [callback]) #
Asynchronous stat(2). The callback gets two arguments (err, stats) where stats is a fs.Stats object. It
looks like this:

{ dev: 2049,
http://nodejs-es.github.io/api/all.html 57/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

ino: 305352,
mode: 16877,
nlink: 12,
uid: 1000,
gid: 1000,
rdev: 0,
size: 4096,
blksize: 4096,
blocks: 8,
atime: '2009-06-29T11:11:55Z',
mtime: '2009-06-29T11:11:40Z',
ctime: '2009-06-29T11:11:40Z' }

See the fs.Stats section below for more information.

fs.lstat(path, [callback]) #
Asynchronous lstat(2). The callback gets two arguments (err, stats) where stats is a fs.Stats object.
lstat() is identical to stat(), except that if path is a symbolic link, then the link itself is stat-ed, not the file that it
refers to.

fs.fstat(fd, [callback]) #
Asynchronous fstat(2). The callback gets two arguments (err, stats) where stats is a fs.Stats object.

fs.statSync(path) #
Synchronous stat(2). Returns an instance of fs.Stats .

fs.lstatSync(path) #
Synchronous lstat(2). Returns an instance of fs.Stats .

fs.fstatSync(fd) #
Synchronous fstat(2). Returns an instance of fs.Stats .

fs.link(srcpath, dstpath, [callback]) #


Asynchronous link(2). No arguments other than a possible exception are given to the completion callback.

fs.linkSync(srcpath, dstpath) #
Synchronous link(2).

fs.symlink(linkdata, path, [callback]) #


Asynchronous symlink(2). No arguments other than a possible exception are given to the completion callback.

fs.symlinkSync(linkdata, path) #
Synchronous symlink(2).

http://nodejs-es.github.io/api/all.html 58/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

fs.readlink(path, [callback]) #
Asynchronous readlink(2). The callback gets two arguments (err, resolvedPath) .

fs.readlinkSync(path) #
Synchronous readlink(2). Returns the resolved path.

fs.realpath(path, [callback]) #
Asynchronous realpath(2). The callback gets two arguments (err, resolvedPath) .

fs.realpathSync(path) #
Synchronous realpath(2). Returns the resolved path.

fs.unlink(path, [callback]) #
Asynchronous unlink(2). No arguments other than a possible exception are given to the completion callback.

fs.unlinkSync(path) #
Synchronous unlink(2).

fs.rmdir(path, [callback]) #
Asynchronous rmdir(2). No arguments other than a possible exception are given to the completion callback.

fs.rmdirSync(path) #
Synchronous rmdir(2).

fs.mkdir(path, mode, [callback]) #


Asynchronous mkdir(2). No arguments other than a possible exception are given to the completion callback.

fs.mkdirSync(path, mode) #
Synchronous mkdir(2).

fs.readdir(path, [callback]) #
Asynchronous readdir(3). Reads the contents of a directory. The callback gets two arguments (err, files)
where files is an array of the names of the files in the directory excluding '.' and '..' .

fs.readdirSync(path) #
Synchronous readdir(3). Returns an array of filenames excluding '.' and '..' .

fs.close(fd, [callback]) #
http://nodejs-es.github.io/api/all.html 59/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

Asynchronous close(2). No arguments other than a possible exception are given to the completion callback.

fs.closeSync(fd) #
Synchronous close(2).

fs.open(path, flags, [mode], [callback]) #


Asynchronous file open. See open(2). Flags can be 'r', 'r+', 'w', 'w+', 'a', or 'a+'. mode defaults to 0666. The
callback gets two arguments (err, fd) .

fs.openSync(path, flags, [mode]) #


Synchronous open(2).

fs.write(fd, buffer, offset, length, position, [callback]) #


Write buffer to the file specified by fd .

offset and length determine the part of the buffer to be written.

position refers to the offset from the beginning of the file where this data should be written. If position is
null , the data will be written at the current position. See pwrite(2).

The callback will be given two arguments (err, written) where written specifies how many bytes were
written.

Note that it is unsafe to use fs.write multiple times on the same file without waiting for the callback. For this
scenario, fs.createWriteStream is strongly recommended.

fs.writeSync(fd, buffer, offset, length, position) #


Synchronous version of buffer-based fs.write() . Returns the number of bytes written.

fs.writeSync(fd, str, position, encoding='utf8') #


Synchronous version of string-based fs.write() . Returns the number of bytes written.

fs.read(fd, buffer, offset, length, position, [callback]) #


Read data from the file specified by fd .

buffer is the buffer that the data will be written to.

offset is offset within the buffer where writing will start.

length is an integer specifying the number of bytes to read.

position is an integer specifying where to begin reading from in the file. If position is null , data will be
read from the current file position.

The callback is given the two arguments, (err, bytesRead) .

http://nodejs-es.github.io/api/all.html 60/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

fs.readSync(fd, buffer, offset, length, position) #


Synchronous version of buffer-based fs.read . Returns the number of bytesRead .

fs.readSync(fd, length, position, encoding) #


Synchronous version of string-based fs.read . Returns the number of bytesRead .

fs.readFile(filename, [encoding], [callback]) #


Asynchronously reads the entire contents of a file. Example:

fs.readFile('/etc/passwd', function (err, data) {


if (err) throw err;
console.log(data);
});

The callback is passed two arguments (err, data) , where data is the contents of the file.

If no encoding is specified, then the raw buffer is returned.

fs.readFileSync(filename, [encoding]) #
Synchronous version of fs.readFile . Returns the contents of the filename .

If encoding is specified then this function returns a string. Otherwise it returns a buffer.

fs.writeFile(filename, data, encoding='utf8', [callback]) #


Asynchronously writes data to a file, replacing the file if it already exists. data can be a string or a buffer.

Example:

fs.writeFile('message.txt', 'Hello Node', function (err) {


if (err) throw err;
console.log('It\'s saved!');
});

fs.writeFileSync(filename, data, encoding='utf8') #


The synchronous version of fs.writeFile .

fs.watchFile(filename, [options], listener) #


Watch for changes on filename . The callback listener will be called each time the file is accessed.

The second argument is optional. The options if provided should be an object containing two members a
boolean, persistent , and interval , a polling value in milliseconds. The default is { persistent: true,
interval: 0 } .

The listener gets two arguments the current stat object and the previous stat object:

http://nodejs-es.github.io/api/all.html 61/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

fs.watchFile(f, function (curr, prev) {


console.log('the current mtime is: ' + curr.mtime);
console.log('the previous mtime was: ' + prev.mtime);
});

These stat objects are instances of fs.Stat .

If you want to be notified when the file was modified, not just accessed you need to compare curr.mtime and
`prev.mtime.

fs.unwatchFile(filename) #
Stop watching for changes on filename .

fs.Stats #
Objects returned from fs.stat() and fs.lstat() are of this type.

stats.isFile()
stats.isDirectory()
stats.isBlockDevice()
stats.isCharacterDevice()
stats.isSymbolicLink() (only valid with fs.lstat())
stats.isFIFO()
stats.isSocket()

fs.ReadStream #
ReadStream is a Readable Stream .

fs.createReadStream(path, [options]) #
Returns a new ReadStream object (See Readable Stream ).

options is an object with the following defaults:

{ flags: 'r',
encoding: null,
fd: null,
mode: 0666,
bufferSize: 64 * 1024
}

options can include start and end values to read a range of bytes from the file instead of the entire file.
Both start and end are inclusive and start at 0. When used, both the limits must be specified always.

An example to read the last 10 bytes of a file which is 100 bytes long:

fs.createReadStream('sample.txt', {start: 90, end: 99});

fs.WriteStream #
http://nodejs-es.github.io/api/all.html 62/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

WriteStream is a Writable Stream .

Event: 'open' #
function (fd) { }

fd is the file descriptor used by the WriteStream.

fs.createWriteStream(path, [options]) #
Returns a new WriteStream object (See Writable Stream ).

options is an object with the following defaults:

{ flags: 'w',
encoding: null,
mode: 0666 }

Path #

Stability: 3 - Stable

Este módulo contiene utilidades para trabajar con rutas de fichero. Casi todos los métodos llevan sólo una
transformaciones en el string. El sistema de archivos no es consulta para comprobar si las rutas son válidos.

Utilice require('path') para utilizarlo. Los siguientes métodos son provistos:

path.normalize(p) #
Normaliza la cadena de texto de una ruta, se encarga de las partes '..' y '.' .

Cuando se encuentra múltiples barras, se reemplazan por una sola; cuando la ruta acaba en barra, se conserva.
En windows se utilizan contrabarras.

Example:

path.normalize('/foo/bar//baz/asdf/quux/..')
// returns
'/foo/bar/baz/asdf'

path.join([path1], [path2], [...]) #


Junta todos los argumentos y normaliza la ruta resultante. Non-string arguments are ignored.

Example:

path.join('/foo', 'bar', 'baz/asdf', 'quux', '..')


// returns
'/foo/bar/baz/asdf'

http://nodejs-es.github.io/api/all.html 63/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

path.join('foo', {}, 'bar')


// returns
'foo/bar'

path.resolve([from ...], to) #


Resuelve to a una ruta absoluta.

If to isn't already absolute from arguments are prepended in right to left order, until an absolute path is
found. If after using all from paths still no absolute path is found, the current working directory is used as well.
The resulting path is normalized, and trailing slashes are removed unless the path gets resolved to the root
directory. Non-string arguments are ignored.

Si to no es absoluta los argumentos from se anteponen ordenados de derecha a izquierda, hasta que se
encuentra una ruta absoluta. Si después de usar todas las rutas de from aún no se encuentra una ruta absoluta,
también se utiliza el directorio actual de trabajo. La ruta resultante se normaliza, y se eliminan las barras finales
a no ser que se resuelva el directorio root.

Otra manera de verlo es como una secuencia de comandos cd en un shell.

path.resolve('foo/bar', '/tmp/file/', '..', 'a/../subfile')

Es como:

cd foo/bar
cd /tmp/file/
cd ..
cd a/../subfile
pwd

La diferencia es que las distintas rutas no necesitan existir e incluso pueden ser ficheros.

Ejemplos:

path.resolve('/foo/bar', './baz')
// returns
'/foo/bar/baz'

path.resolve('/foo/bar', '/tmp/file/')
// returns
'/tmp/file'

path.resolve('wwwroot', 'static_files/png/', '../gif/image.gif')


// if currently in /home/myself/node, it returns
'/home/myself/node/wwwroot/static_files/gif/image.gif'

path.relative(from, to) #
Solve the relative path from from to to .

At times we have two absolute paths, and we need to derive the relative path from one to the other. This is
actually the reverse transform of path.resolve , which means we see that:

http://nodejs-es.github.io/api/all.html 64/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

path.resolve(from, path.relative(from, to)) == path.resolve(to)

Ejemplos:

path.relative('C:\\orandea\\test\\aaa', 'C:\\orandea\\impl\\bbb')
// returns
'..\\..\\impl\\bbb'

path.relative('/data/orandea/test/aaa', '/data/orandea/impl/bbb')
// returns
'../../impl/bbb'

path.dirname(p) #
Devuelve el nombre de directorio de una ruta. Semejante al comando de Unix dirname .

Ejemplo:

path.dirname('/foo/bar/baz/asdf/quux')
// returns
'/foo/bar/baz/asdf'

path.basename(p, [ext]) #
Devuelve la última parte de una ruta. Semejante al comando de Unix basename .

Ejemplo:

path.basename('/foo/bar/baz/asdf/quux.html')
// returns
'quux.html'

path.basename('/foo/bar/baz/asdf/quux.html', '.html')
// returns
'quux'

path.extname(p) #
Devuelve la extensión de la ruta. Todo lo que hay después del último '.' en la última parte de la ruta. Si no hay '.'
en la última parte de la ruta o el único '.' es el primer carácter, entonces devuelve un string vacío. Ejemplos:

path.extname('index.html')
// returns
'.html'

path.extname('index.')
// returns
'.'

path.extname('index')
// returns
''

http://nodejs-es.github.io/api/all.html 65/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

net #

Stability: 3 - Stable

The net module provides you with an asynchronous network wrapper. It contains methods for creating both
servers and clients (called streams). You can include this module with require('net');

net.createServer([options], [connectionListener]) #
Creates a new TCP server. The connectionListener argument is automatically set as a listener for the
'connection' event.

options is an object with the following defaults:

{ allowHalfOpen: false
}

If allowHalfOpen is true , then the socket won't automatically send a FIN packet when the other end of the
socket sends a FIN packet. The socket becomes non-readable, but still writable. You should call the end()
method explicitly. See 'end' event for more information.

Here is an example of a echo server which listens for connections on port 8124:

var net = require('net');


var server = net.createServer(function(c) { //'connection' listener
console.log('server connected');
c.on('end', function() {
console.log('server disconnected');
});
c.write('hello\r\n');
c.pipe(c);
});
server.listen(8124, function() { //'listening' listener
console.log('server bound');
});

Test this by using telnet :

telnet localhost 8124

To listen on the socket /tmp/echo.sock the third line from the last would just be changed to

server.listen('/tmp/echo.sock', function() { //'listening' listener

Use nc to connect to a UNIX domain socket server:

nc -U /tmp/echo.sock

http://nodejs-es.github.io/api/all.html 66/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

net.connect(options, [connectionListener]) #

net.createConnection(options, [connectionListener]) #
Constructs a new socket object and opens the socket to the given location. When the socket is established, the
'connect' event will be emitted.

For TCP sockets, options argument should be an object which specifies:

port : Port the client should connect to (Required).


host : Host the client should connect to. Defaults to 'localhost' .

For UNIX domain sockets, options argument should be an object which specifies:

path: Path the client should connect to (Required).

Common options are:

allowHalfOpen: if true, the socket won't automatically send a FIN packet when the other end of the
socket sends a FIN packet. Defaults to false. See 'end' event for more information.

The connectListener parameter will be added as an listener for the 'connect' event.

Here is an example of a client of echo server as described previously:

var net = require('net');


var client = net.connect({port: 8124},
function() { //'connect' listener
console.log('client connected');
client.write('world!\r\n');
});
client.on('data', function(data) {
console.log(data.toString());
client.end();
});
client.on('end', function() {
console.log('client disconnected');
});

To connect on the socket /tmp/echo.sock the second line would just be changed to

var client = net.connect({path: '/tmp/echo.sock'},

net.connect(port, [host], [connectListener]) #

net.createConnection(port, [host], [connectListener]) #


Creates a TCP connection to port on host . If host is omitted, 'localhost' will be assumed. The
connectListener parameter will be added as an listener for the 'connect' event.

net.connect(path, [connectListener]) #

net.createConnection(path, [connectListener]) #
Creates unix socket connection to path . The connectListener parameter will be added as an listener for the
'connect' event.
http://nodejs-es.github.io/api/all.html 67/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

Class: net.Server #
This class is used to create a TCP or UNIX server. A server is a net.Socket that can listen for new incoming
connections.

server.listen(port, [host], [listeningListener]) #


Begin accepting connections on the specified port and host . If the host is omitted, the server will accept
connections directed to any IPv4 address ( INADDR_ANY ). A port value of zero will assign a random port.

This function is asynchronous. When the server has been bound, 'listening' event will be emitted. the last
parameter listeningListener will be added as an listener for the 'listening' event.

One issue some users run into is getting EADDRINUSE errors. This means that another server is already running
on the requested port. One way of handling this would be to wait a second and then try again. This can be done
with

server.on('error', function (e) {


if (e.code == 'EADDRINUSE') {
console.log('Address in use, retrying...');
setTimeout(function () {
server.close();
server.listen(PORT, HOST);
}, 1000);
}
});

(Note: All sockets in Node set SO_REUSEADDR already)

server.listen(path, [listeningListener]) #
Start a UNIX socket server listening for connections on the given path .

This function is asynchronous. When the server has been bound, 'listening' event will be emitted. the last
parameter listeningListener will be added as an listener for the 'listening' event.

server.close([cb]) #
Stops the server from accepting new connections. This function is asynchronous, the server is finally closed when
the server emits a 'close' event. Optionally, you can pass a callback to listen for the 'close' event.

server.address() #
Returns the bound address and port of the server as reported by the operating system. Useful to find which port
was assigned when giving getting an OS-assigned address. Returns an object with two properties, e.g.
{"address":"127.0.0.1", "port":2121}

Example:

var server = net.createServer(function (socket) {


socket.end("goodbye\n");
});

http://nodejs-es.github.io/api/all.html 68/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

// grab a random port.


server.listen(function() {
address = server.address();
console.log("opened server on %j", address);
});

Don't call server.address() until the 'listening' event has been emitted.

server.maxConnections #
Set this property to reject connections when the server's connection count gets high.

server.connections #
The number of concurrent connections on the server.

net.Server is an EventEmitter with the following events:

Event: 'listening' #
Emitted when the server has been bound after calling server.listen .

Event: 'connection' #
Socket object The connection object

Emitted when a new connection is made. socket is an instance of net.Socket .

Event: 'close' #
Emitted when the server closes.

Event: 'error' #
Error Object

Emitted when an error occurs. The 'close' event will be called directly following this event. See example in
discussion of server.listen .

Class: net.Socket #
This object is an abstraction of a TCP or UNIX socket. net.Socket instances implement a duplex Stream
interface. They can be created by the user and used as a client (with connect() ) or they can be created by Node
and passed to the user through the 'connection' event of a server.

new net.Socket([options]) #
Construct a new socket object.

http://nodejs-es.github.io/api/all.html 69/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

options is an object with the following defaults:

{ fd: null
type: null
allowHalfOpen: false
}

fd allows you to specify the existing file descriptor of socket. type specified underlying protocol. It can be
'tcp4' , 'tcp6' , or 'unix' . About allowHalfOpen , refer to createServer() and 'end' event.

socket.connect(port, [host], [connectListener]) #


socket.connect(path, [connectListener]) #
Opens the connection for a given socket. If port and host are given, then the socket will be opened as a TCP
socket, if host is omitted, localhost will be assumed. If a path is given, the socket will be opened as a unix
socket to that path.

Normally this method is not needed, as net.createConnection opens the socket. Use this only if you are
implementing a custom Socket or if a Socket is closed and you want to reuse it to connect to another server.

This function is asynchronous. When the 'connect' event is emitted the socket is established. If there is a problem
connecting, the 'connect' event will not be emitted, the 'error' event will be emitted with the exception.

The connectListener parameter will be added as an listener for the 'connect' event.

socket.bufferSize #
net.Socket has the property that socket.write() always works. This is to help users get up and running
quickly. The computer cannot always keep up with the amount of data that is written to a socket - the network
connection simply might be too slow. Node will internally queue up the data written to a socket and send it out
over the wire when it is possible. (Internally it is polling on the socket's file descriptor for being writable).

The consequence of this internal buffering is that memory may grow. This property shows the number of
characters currently buffered to be written. (Number of characters is approximately equal to the number of bytes
to be written, but the buffer may contain strings, and the strings are lazily encoded, so the exact number of bytes
is not known.)

Users who experience large or growing bufferSize should attempt to "throttle" the data flows in their program
with pause() and resume() .

socket.setEncoding([encoding]) #
Sets the encoding (either 'ascii' , 'utf8' , or 'base64' ) for data that is received. Defaults to null .

socket.write(data, [encoding], [callback]) #


Sends data on the socket. The second parameter specifies the encoding in the case of a string--it defaults to UTF8
encoding.

Returns true if the entire data was flushed successfully to the kernel buffer. Returns false if all or part of the
data was queued in user memory. 'drain' will be emitted when the buffer is again free.

http://nodejs-es.github.io/api/all.html 70/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

The optional callback parameter will be executed when the data is finally written out - this may not be
immediately.

socket.end([data], [encoding]) #
Half-closes the socket. i.e., it sends a FIN packet. It is possible the server will still send some data.

If data is specified, it is equivalent to calling socket.write(data, encoding) followed by socket.end() .

socket.destroy() #
Ensures that no more I/O activity happens on this socket. Only necessary in case of errors (parse error or so).

socket.pause() #
Pauses the reading of data. That is, 'data' events will not be emitted. Useful to throttle back an upload.

socket.resume() #
Resumes reading after a call to pause() .

socket.setTimeout(timeout, [callback]) #
Sets the socket to timeout after timeout milliseconds of inactivity on the socket. By default net.Socket do
not have a timeout.

When an idle timeout is triggered the socket will receive a 'timeout' event but the connection will not be
severed. The user must manually end() or destroy() the socket.

If timeout is 0, then the existing idle timeout is disabled.

The optional callback parameter will be added as a one time listener for the 'timeout' event.

socket.setNoDelay([noDelay]) #
Disables the Nagle algorithm. By default TCP connections use the Nagle algorithm, they buffer data before
sending it off. Setting true for noDelay will immediately fire off data each time socket.write() is called.
noDelay defaults to true .

socket.setKeepAlive([enable], [initialDelay]) #
Enable/disable keep-alive functionality, and optionally set the initial delay before the first keepalive probe is sent
on an idle socket. enable defaults to false .

Set initialDelay (in milliseconds) to set the delay between the last data packet received and the first
keepalive probe. Setting 0 for initialDelay will leave the value unchanged from the default (or previous) setting.
Defaults to 0 .

http://nodejs-es.github.io/api/all.html 71/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

socket.address() #
Returns the bound address and port of the socket as reported by the operating system. Returns an object with
two properties, e.g. {"address":"192.168.57.1", "port":62053}

socket.remoteAddress #
The string representation of the remote IP address. For example, '74.125.127.100' or
'2001:4860:a005::68' .

socket.remotePort #
The numeric representation of the remote port. For example, 80 or 21 .

socket.bytesRead #
The amount of received bytes.

socket.bytesWritten #
The amount of bytes sent.

net.Socket instances are EventEmitters with the following events:

Event: 'connect' #
Emitted when a socket connection is successfully established. See connect() .

Event: 'data' #
Buffer object

Emitted when data is received. The argument data will be a Buffer or String . Encoding of data is set by
socket.setEncoding() . (See the Readable Stream section for more information.)

Note that the data will be lost if there is no listener when a Socket emits a 'data' event.

Event: 'end' #
Emitted when the other end of the socket sends a FIN packet.

By default ( allowHalfOpen == false ) the socket will destroy its file descriptor once it has written out its
pending write queue. However, by setting allowHalfOpen == true the socket will not automatically end()
its side allowing the user to write arbitrary amounts of data, with the caveat that the user is required to end()
their side now.

Event: 'timeout' #
Emitted if the socket times out from inactivity. This is only to notify that the socket has been idle. The user must
http://nodejs-es.github.io/api/all.html 72/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

manually close the connection.

See also: socket.setTimeout()

Event: 'drain' #
Emitted when the write buffer becomes empty. Can be used to throttle uploads.

See also: the return values of socket.write()

Event: 'error' #
Error object

Emitted when an error occurs. The 'close' event will be called directly following this event.

Event: 'close' #
had_error Boolean true if the socket had a transmission error

Emitted once the socket is fully closed. The argument had_error is a boolean which says if the socket was
closed due to a transmission error.

net.isIP(input) #
Tests if input is an IP address. Returns 0 for invalid strings, returns 4 for IP version 4 addresses, and returns 6
for IP version 6 addresses.

net.isIPv4(input) #
Returns true if input is a version 4 IP address, otherwise returns false.

net.isIPv6(input) #
Returns true if input is a version 6 IP address, otherwise returns false.

UDP / Sockets de Datagrama #

Stability: 3 - Stable

Los sockets de datagrama están disponibles a través de require('dgram') . Normalmente los datagramas se
manejan como mensajes IP/UDP pero también se pueden usar a través de sockets de dominio Unix.

Evento: 'message' #
function (msg, rinfo) { }

Emitido cuando está disponible un nuevo datagrama en el socket. msg es un Buffer y rinfo` es un objeto
con la dirección de quien lo envía y el número de bytes que contiene el datagrama.

http://nodejs-es.github.io/api/all.html 73/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

Evento: 'listening' #
function () { }

Emitido cuando un socket empieza a escuchar la llegada de datagramas. Esto ocurre tan pronto como son
creados los sockets UDP. Los sockets de dominio Unix no empiezan a escuchar hasta que se llama implícitamente
a bind() .

Evento: 'close' #
function () { }

Emitido cuando se cierra un socket con close() . No se emitirán nuevos message en este socket.

dgram.createSocket(type, [callback]) #
Crea un socket de datagrama del tipo especificado. Los tipos válidos son: udp4 , udp6 y unix_dgram .

Recibe un callback opcional que se añade como listener de los eventos message .

dgram.send(buf, offset, length, path, [callback]) #


Para los sockets de datagrama del dominio Unix, la dirección de destion es un nombre de ruta en sistema de
ficheros. Se puede pasar un callback opcional que se invoca cuando se completa la llamada a sendto por parte
del SO. No es seguro reutilizar buf hasta que se ha invocado el callback. Hay que tener en cuenta que a no ser
que el socket este asociado a un nombre de ruta con bind() no hay manera de recibir mensajes en el socket.

Ejemplo de envío de un mensaje al syslogd en OSX via un socket de dominio Unix /var/run/syslog :

var dgram = require('dgram');


var message = new Buffer("Un mensaje de log.");
var client = dgram.createSocket("unix_dgram");
client.send(message, 0, message.length, "/var/run/syslog",
function (err, bytes) {
if (err) {
throw err;
}
console.log("Se han escrito " + bytes + " bytes en el socket.");
});

dgram.send(buf, offset, length, port, address, [callback]) #


Para los sockets UDP, el puerto y la dirección IP de destino tienen que especificarse. Se puede pasar un string al
parámetro address , y se podrá resolver por DNS. Se puede especificar un callback opcional para detectar
cualquier error de DNS y cuando puede volverse a usar buf .
Tener en cuenta que las búsquedas de DNS retrasarán el tiempo del envío, al menos hasta el siguiente tick. La
única manera de asegurarse de que se ha realizado un envío es mediante el callback.

Ejemplo de enviar un paquete UDP a un puerto aleatorio de localhost ;

var dgram = require('dgram');


var message = new Buffer("Algunos bytes");
var client = dgram.createSocket("udp4");

http://nodejs-es.github.io/api/all.html 74/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

client.send(message, 0, message.length, 41234, "localhost");


client.close();

dgram.bind(path) #
Para los sockets de datagrama de dominio Unix, empezar a escuchar datagramas entrantes en el socket
especificado por path . Notar que los clientes pueden hacer send() sin haber hecho bind() , pero no se
recibirá ningún datagrama sin haber hecho un bind() .

Ejemplo de un servidor de datagramas de dominio Unix, que devuelve el eco de los mensajes que recibe:

var dgram = require("dgram");


var serverPath = "/tmp/dgram_server_sock";
var server = dgram.createSocket("unix_dgram");

server.on("message", function (msg, rinfo) {


console.log("recibido: " + msg + " de " + rinfo.address);
server.send(msg, 0, msg.length, rinfo.address);
});

server.on("listening", function () {
console.log("servidor escuchando " + server.address().address);
})

server.bind(serverPath);

Ejemplo de un cliente de datagramas de dominio Unix que habla con el servidor:

var dgram = require("dgram");


var serverPath = "/tmp/dgram_server_sock";
var clientPath = "/tmp/dgram_client_sock";

var message = new Buffer("Un mensaje el " + (new Date()));

var client = dgram.createSocket("unix_dgram");

client.on("message", function (msg, rinfo) {


console.log("recibido: " + msg + " de " + rinfo.address);
});

client.on("listening", function () {
console.log("cliente escuchando " + client.address().address);
client.send(message, 0, message.length, serverPath);
});

client.bind(clientPath);

dgram.bind(port, [address]) #
Para los sockets UDP, hay que escuhar los datagramas en un port específico y en el address opcional. Si no se
especifica address , el SO intentará escuchar en todas las direcciones.

Ejemplo de un servidor UDP escuchando en el puerto 41234:

http://nodejs-es.github.io/api/all.html 75/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

var dgram = require("dgram");

var server = dgram.createSocket("udp4");

server.on("message", function (msg, rinfo) {


console.log("el servidor ha recibido: " + msg + " de " +
rinfo.address + ":" + rinfo.port);
});

server.on("listening", function () {
var address = server.address();
console.log("servidor escuchando " +
address.address + ":" + address.port);
});

server.bind(41234);
// server listening 0.0.0.0:41234

dgram.close() #
Cierra el socket subyacente y para de escuchar datos en él. Los sockets UDP automáticamente se ponen a
escuchar mensjaes, incluso si no han llamado a bind() .

dgram.address() #
Devuelve un objeto que contiene la información de la dirección de un socket. Para los sockets UDP, este objeto
contendrá la address y el port . Para los sockets de dominio Unix, solo contendrá la address .

dgram.setBroadcast(flag) #
Establece o borra la opción del socket SO_BROADCAST . Cuando se activa esta opción, los paquetes UDP se
pueden enviar una dirección de broadcast de un interfaz local.

dgram.setTTL(ttl) #
Establece la opción de socket IP_TTL . TTL significa "Time to Live", pero en este contexto especifica el número
de saltos IP que se permite hacer al paquete. Cada router o gateway que reenvíe un paquete decrementa el TTL.
Si un router decrementa el TTL a 0, no se reenviará.
El cambio de los valores del TTL es un uso típico para probar la red o con multicasting.

El argumento que se le pasa a setTTL() es el número de saltos entre 1 y 255. Por defecto en la mayoría de
sistemas es 64.

dgram.setMulticastTTL(ttl) #
Establece la opción de socket IP_MULTICAST_TTL . TTL significa "Time to Live", pero en este contexto especifica
el número de saltos IP que se permite hacer al paquete. Cada router o gateway que reenvíe un paquete
decrementa el TTL. Si un router decrementa el TTL a 0, no se reenviará.

El argumento que se le pasa a setMulticastTTL() es el número de saltos entre 0 y 255. Por defecto en la
mayoría de sistemas es 64.

http://nodejs-es.github.io/api/all.html 76/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

dgram.setMulticastLoopback(flag) #
Establece o borra la opción de socket IP_MULTICAST_LOOP . Cuand esta opción está activa,
también se recibirán paquetes multicast en el interfaz local.

dgram.addMembership(multicastAddress, #
[multicastInterface])
Comunica al kernel la suscripción a un grupo multicast con la opción de socket IP_ADD_MEMBERSHIP .

Si no se especifica multicastAddress , el SO intentará suscribir todos los interfaces válidos.

dgram.dropMembership(multicastAddress, #
[multicastInterface])
El contrario de addMembership - comunica al kernel el abandono de un grupo multicast con la opción de socket
IP_DROP_MEMBERSHIP . Este método se llama automáticamente por el kernel cuando se cierra el socket o el
proceso termina, así que la mayoría de aplicaciones nunca tendrán que llamarlo.

Si no se especifica multicastAddress , el SO intentará suscribir todos los interfaces válidos.

DNS #

Stability: 3 - Stable

Use require('dns') to access this module. All methods in the dns module use C-Ares except for dns.lookup
which uses getaddrinfo(3) in a thread pool. C-Ares is much faster than getaddrinfo but the system
resolver is more constant with how other programs operate. When a user does net.connect(80,
'google.com') or http.get({ host: 'google.com' }) the dns.lookup method is used. Users who need
to do a large number of look ups quickly should use the methods that go through C-Ares.

Here is an example which resolves 'www.google.com' then reverse resolves the IP addresses which are
returned.

var dns = require('dns');

dns.resolve4('www.google.com', function (err, addresses) {


if (err) throw err;

console.log('addresses: ' + JSON.stringify(addresses));

addresses.forEach(function (a) {
dns.reverse(a, function (err, domains) {
if (err) {
console.log('reverse for ' + a + ' failed: ' +
err.message);
} else {
console.log('reverse for ' + a + ': ' +
JSON.stringify(domains));
}
});
});
});

http://nodejs-es.github.io/api/all.html 77/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

dns.lookup(domain, [family], callback) #


Resolves a domain (e.g. 'google.com' ) into the first found A (IPv4) or AAAA (IPv6) record. The family can
be the integer 4 or 6 . Defaults to null that indicates both Ip v4 and v6 address family.

The callback has arguments (err, address, family) . The address argument is a string representation of a
IP v4 or v6 address. The family argument is either the integer 4 or 6 and denotes the family of address (not
necessarily the value initially passed to lookup ).

dns.resolve(domain, [rrtype], callback) #


Resolves a domain (e.g. 'google.com' ) into an array of the record types specified by rrtype. Valid rrtypes are
'A' (IPV4 addresses, default), 'AAAA' (IPV6 addresses), 'MX' (mail exchange records), 'TXT' (text
records), 'SRV' (SRV records), 'PTR' (used for reverse IP lookups), 'NS' (name server records) and
'CNAME' (canonical name records).

The callback has arguments (err, addresses) . The type of each item in addresses is determined by the
record type, and described in the documentation for the corresponding lookup methods below.

On error, err would be an instanceof Error object, where err.errno is one of the error codes listed below
and err.message is a string describing the error in English.

dns.resolve4(domain, callback) #
The same as dns.resolve() , but only for IPv4 queries ( A records). addresses is an array of IPv4 addresses
(e.g. ['74.125.79.104', '74.125.79.105', '74.125.79.106'] ).

dns.resolve6(domain, callback) #
The same as dns.resolve4() except for IPv6 queries (an AAAA query).

dns.resolveMx(domain, callback) #
The same as dns.resolve() , but only for mail exchange queries ( MX records).

addresses is an array of MX records, each with a priority and an exchange attribute (e.g. [{'priority': 10,
'exchange': 'mx.example.com'},...] ).

dns.resolveTxt(domain, callback) #
The same as dns.resolve() , but only for text queries ( TXT records). addresses is an array of the text
records available for domain (e.g., ['v=spf1 ip4:0.0.0.0 ~all'] ).

dns.resolveSrv(domain, callback) #
The same as dns.resolve() , but only for service records ( SRV records). addresses is an array of the SRV
records available for domain . Properties of SRV records are priority, weight, port, and name (e.g.,
[{'priority': 10, {'weight': 5, 'port': 21223, 'name': 'service.example.com'}, ...] ).

dns.reverse(ip, callback) #
Reverse resolves an ip address to an array of domain names.

http://nodejs-es.github.io/api/all.html 78/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

The callback has arguments (err, domains) .

dns.resolveNs(domain, callback) #
The same as dns.resolve() , but only for name server records ( NS records). addresses is an array of the
name server records available for domain (e.g., ['ns1.example.com', 'ns2.example.com'] ).

dns.resolveCname(domain, callback) #
The same as dns.resolve() , but only for canonical name records ( CNAME records). addresses is an array of
the canonical name records available for domain (e.g., ['bar.example.com'] ).

If there an an error, err will be non-null and an instanceof the Error object.

Each DNS query can return an error code.

dns.TEMPFAIL: timeout, SERVFAIL or similar.


dns.PROTOCOL: got garbled reply.
dns.NXDOMAIN: domain does not exists.
dns.NODATA: domain exists but no data of reqd type.
dns.NOMEM: out of memory while processing.
dns.BADQUERY: the query is malformed.

HTTP #
Para usar el servidor y el cliente HTTP se debe añadir require('http') .

Las interfaces HTTP en Node están diseñadas para soportar muchas de las características del protocolo que
tradicionalmente han sido difíciles de usar. En particular, los mensajes grandes, seguramente fragmentado. La
interfaz se asegura de que las peticiones o respuestas nunca se almacenen completamente en un búfer--se
permite al usuario hacer stream de datos.

Las cabeceras de los mensajes HTTP se representan por un objeto como este: { 'content-length': '123', 'content-
type': 'text/plain', 'connection': 'keep-alive', 'accept': '/' }

Las claves se convierten a minúsculas. Los valores no se modifican.

Para soportar el espectro completo de las posibles aplicaciones HTTP, la API HTTP de Node es de muy bajo
nivel. Se encarga únicamente de manejar el stream y del parsing del mensaje. Parsea el mensaje en sus cabeceras
y body pero no parsea las cabeceras o el body.

http.Server #
Es un EventEmitter con los siguientes eventos:

Evento: 'request' #
function (request, response) { }

request es una instancia de http.ServerRequest y response es una instancia de http.ServerResponse

http://nodejs-es.github.io/api/all.html 79/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

Evento: 'connection' #
function (stream) { }

Cuando se establece un nuevo stream TCP. stream es un objeto de tipo net.Stream . Generalmente los
usuarios no querrán acceder a este evento. También se puede acceder el stream desde request.connection .

Evento: 'close' #
function (errno) { }

Emitido cuando se cierra el servidor.

Evento: 'request' #
function (request, response) {}

Emitido cada vez que se produce una petición. Nótese que pueden producirse múltiples peticiones para cada
conexión (en el caso de las conexiones keep-alive).

Evento: 'checkContinue' #
function (request, response) {}

Emitido cada vez que se recibe una petición con un http Expect: 100-continue. Si no se está escuchando a este
evento, el servidor responderá automáticamente con un 100 Continue.

Para tratar este evento se tiene que llamar a response.writeContinue si el cliente quisiera seguir con el envío
la petición de body, o generar una respuesta HTTP adecuada (ej. 400 Bad Request) si el cliente no quisiera
continuar con el envío de la petición del body.

Tener en cuenta que cuando se emite y se trata este evento, el evento request no se emitirá.

Evento: 'upgrade' #
function (request, socket, head)

Se emite cada vez que un cliente pide una actualización http. Si este evento no se está escuchando, entonces se
cerrarán las conexiones de los clientes que esten pidiendo una actualización.

request es el argumento para la petición http, como en el evento request.


socket es el socket de red entre el servidor y el cliente.
head es una instancia de Buffer, el primer paquete del stream actualizado, puede estar vacío.

Después de emitir este evento, el socket de la petición no tendrá un listener del evento data , esto significa que
necesitarás asociarlo para tratar los datos enviados al servidor en ese socket.

Evento: 'clientError' #
function (exception) {}

Si la conexión de un cliente emite un evento de 'error' - será tratado aquí.


http://nodejs-es.github.io/api/all.html 80/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

http.createServer(requestListener) #
Devuelve un nuevo objeto de servidor web.

requestListener es una función que se añade automáticamente al evento 'request' .

server.listen(port, [hostname], [callback]) #


Begin accepting connections on the specified port and hostname. If the hostname is omitted, the server will
accept connections directed to any IPv4 address ( INADDR_ANY ).

To listen to a unix socket, supply a filename instead of port and hostname.

This function is asynchronous. The last parameter callback will be called when the server has been bound to
the port.

server.listen(path, [callback]) #
Start a UNIX socket server listening for connections on the given path .

This function is asynchronous. The last parameter callback will be called when the server has been bound.

server.close() #
Stops the server from accepting new connections.

http.ServerRequest #
This object is created internally by a HTTP server -- not by the user -- and passed as the first argument to a
'request' listener.

This is an EventEmitter with the following events:

Event: 'data' #
function (chunk) { }

Emitted when a piece of the message body is received.

Example: A chunk of the body is given as the single argument. The transfer-encoding has been decoded. The
body chunk is a string. The body encoding is set with request.setBodyEncoding() .

Event: 'end' #
function () { }

Emitted exactly once for each message. No arguments. After emitted no other events will be emitted on the
request.

request.method #
http://nodejs-es.github.io/api/all.html 81/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

The request method as a string. Read only. Example: 'GET' , 'DELETE' .

request.url #
Request URL string. This contains only the URL that is present in the actual HTTP request. If the request is:

GET /status?name=ryan HTTP/1.1\r\n


Accept: text/plain\r\n
\r\n

Then request.url will be:

'/status?name=ryan'

If you would like to parse the URL into its parts, you can use require('url').parse(request.url) .
Example:

node> require('url').parse('/status?name=ryan')
{ href: '/status?name=ryan',
search: '?name=ryan',
query: 'name=ryan',
pathname: '/status' }

If you would like to extract the params from the query string, you can use the
require('querystring').parse function, or pass true as the second argument to
require('url').parse . Example:

node> require('url').parse('/status?name=ryan', true)


{ href: '/status?name=ryan',
search: '?name=ryan',
query: { name: 'ryan' },
pathname: '/status' }

request.headers #
Read only.

request.trailers #
Read only; HTTP trailers (if present). Only populated after the 'end' event.

request.httpVersion #
The HTTP protocol version as a string. Read only. Examples: '1.1' , '1.0' . Also
request.httpVersionMajor is the first integer and request.httpVersionMinor is the second.

request.setEncoding(encoding=null) #
Set the encoding for the request body. Either 'utf8' or 'binary' . Defaults to null , which means that the
http://nodejs-es.github.io/api/all.html 82/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

'data' event will emit a Buffer object..

request.pause() #
Pauses request from emitting events. Useful to throttle back an upload.

request.resume() #
Resumes a paused request.

request.connection #
The net.Stream object associated with the connection.

With HTTPS support, use request.connection.verifyPeer() and request.connection.getPeerCertificate() to obtain


the client's authentication details.

http.ServerResponse #
This object is created internally by a HTTP server--not by the user. It is passed as the second parameter to the
'request' event. It is a Writable Stream .

response.writeContinue() #
Sends a HTTP/1.1 100 Continue message to the client, indicating that the request body should be sent. See the
the checkContinue event on Server .

response.writeHead(statusCode, [reasonPhrase], [headers]) #


Sends a response header to the request. The status code is a 3-digit HTTP status code, like 404 . The last
argument, headers , are the response headers. Optionally one can give a human-readable reasonPhrase as
the second argument.

Example:

var body = 'hello world';


response.writeHead(200, {
'Content-Length': body.length,
'Content-Type': 'text/plain' });

This method must only be called once on a message and it must be called before response.end() is called.

If you call response.write() or response.end() before calling this, the implicit/mutable headers will be
calculated and call this function for you.

response.statusCode #
When using implicit headers (not calling response.writeHead() explicitly), this property controls the status
code that will be send to the client when the headers get flushed.

http://nodejs-es.github.io/api/all.html 83/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

Example:

response.statusCode = 404;

response.setHeader(name, value) #
Sets a single header value for implicit headers. If this header already exists in the to-be-sent headers, it's value
will be replaced. Use an array of strings here if you need to send multiple headers with the same name.

Example:

response.setHeader("Content-Type", "text/html");

or

response.setHeader("Set-Cookie", ["type=ninja", "language=javascript"]);

response.getHeader(name) #
Reads out a header that's already been queued but not sent to the client. Note that the name is case insensitive.
This can only be called before headers get implicitly flushed.

Example:

var contentType = response.getHeader('content-type');

response.removeHeader(name) #
Removes a header that's queued for implicit sending.

Example:

response.removeHeader("Content-Encoding");

response.write(chunk, encoding='utf8') #
If this method is called and response.writeHead() has not been called, it will switch to implicit header mode
and flush the implicit headers.

This sends a chunk of the response body. This method may be called multiple times to provide successive parts of
the body.

chunk can be a string or a buffer. If chunk is a string, the second parameter specifies how to encode it into a
byte stream. By default the encoding is 'utf8' .

Note: This is the raw HTTP body and has nothing to do with higher-level multi-part body encodings that may be
used.

http://nodejs-es.github.io/api/all.html 84/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

The first time response.write() is called, it will send the buffered header information and the first body to
the client. The second time response.write() is called, Node assumes you're going to be streaming data, and
sends that separately. That is, the response is buffered up to the first chunk of body.

response.addTrailers(headers) #
This method adds HTTP trailing headers (a header but at the end of the message) to the response.

Trailers will only be emitted if chunked encoding is used for the response; if it is not (e.g., if the request was
HTTP/1.0), they will be silently discarded.

Note that HTTP requires the Trailer header to be sent if you intend to emit trailers, with a list of the header
fields in its value. E.g.,

response.writeHead(200, { 'Content-Type': 'text/plain',


'Trailer': 'TraceInfo' });
response.write(fileData);
response.addTrailers({'Content-MD5': "7895bf4b8828b55ceaf47747b4bca667"});
response.end();

response.end([data], [encoding]) #
This method signals to the server that all of the response headers and body has been sent; that server should
consider this message complete. The method, response.end() , MUST be called on each response.

If data is specified, it is equivalent to calling response.write(data, encoding) followed by


response.end() .

http.request(options, callback) #
Node maintains several connections per server to make HTTP requests. This function allows one to transparently
issue requests.

Options:

host: A domain name or IP address of the server to issue the request to.
port: Port of remote server.
method: A string specifying the HTTP request method. Possible values: 'GET' (default), 'POST', 'PUT',
and 'DELETE'.
path: Request path. Should include query string and fragments if any. E.G. '/index.html?page=12'
headers: An object containing request headers.

http.request() returns an instance of the http.ClientRequest class. The ClientRequest instance is a


writable stream. If one needs to upload a file with a POST request, then write to the ClientRequest object.

Example:

var options = {
host: 'www.google.com',
port: 80,
path: '/upload',
method: 'POST'
};

http://nodejs-es.github.io/api/all.html 85/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

var req = http.request(options, function(res) {


console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('BODY: ' + chunk);
});
});

// write data to request body


req.write('data\n');
req.write('data\n');
req.end();

Note that in the example req.end() was called. With http.request() one must always call req.end() to
signify that you're done with the request - even if there is no data being written to the request body.

If any error is encountered during the request (be that with DNS resolution, TCP level errors, or actual HTTP
parse errors) an 'error' event is emitted on the returned request object.

There are a few special headers that should be noted.

Sending a 'Connection: keep-alive' will notify Node that the connection to the server should be persisted
until the next request.
Sending a 'Content-length' header will disable the default chunked encoding.
Sending an 'Expect' header will immediately send the request headers. Usually, when sending 'Expect: 100-
continue', you should both set a timeout and listen for the continue event. See RFC2616 Section 8.2.3 for
more information.

http.get(options, callback) #
Since most requests are GET requests without bodies, Node provides this convenience method. The only
difference between this method and http.request() is that it sets the method to GET and calls req.end()
automatically.

Example:

var options = {
host: 'www.google.com',
port: 80,
path: '/index.html'
};

http.get(options, function(res) {
console.log("Got response: " + res.statusCode);
}).on('error', function(e) {
console.log("Got error: " + e.message);
});

http.Agent #
http.getAgent(host, port) #
http.request() uses a special Agent for managing multiple connections to an HTTP server. Normally
Agent instances should not be exposed to user code, however in certain situations it's useful to check the status
http://nodejs-es.github.io/api/all.html 86/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

of the agent. The http.getAgent() function allows you to access the agents.

Event: 'upgrade' #
function (request, socket, head)

Emitted each time a server responds to a request with an upgrade. If this event isn't being listened for, clients
receiving an upgrade header will have their connections closed.

See the description of the upgrade event for http.Server for further details.

Event: 'continue' #
function ()

Emitted when the server sends a '100 Continue' HTTP response, usually because the request contained 'Expect:
100-continue'. This is an instruction that the client should send the request body.

agent.maxSockets #
By default set to 5. Determines how many concurrent sockets the agent can have open.

agent.sockets #
An array of sockets currently in use by the Agent. Do not modify.

agent.queue #
A queue of requests waiting to be sent to sockets.

http.ClientRequest #
This object is created internally and returned from http.request() . It represents an in­progress request
whose header has already been queued. The header is still mutable using the setHeader(name, value) ,
getHeader(name) , removeHeader(name) API. The actual header will be sent along with the first data chunk
or when closing the connection.

To get the response, add a listener for 'response' to the request object. 'response' will be emitted from the
request object when the response headers have been received. The 'response' event is executed with one
argument which is an instance of http.ClientResponse .

During the 'response' event, one can add listeners to the response object; particularly to listen for the
'data' event. Note that the 'response' event is called before any part of the response body is received, so
there is no need to worry about racing to catch the first part of the body. As long as a listener for 'data' is
added during the 'response' event, the entire body will be caught.

// Good
request.on('response', function (response) {
response.on('data', function (chunk) {
console.log('BODY: ' + chunk);
});
http://nodejs-es.github.io/api/all.html 87/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

});

// Bad - misses all or part of the body


request.on('response', function (response) {
setTimeout(function () {
response.on('data', function (chunk) {
console.log('BODY: ' + chunk);
});
}, 10);
});

This is a Writable Stream .

This is an EventEmitter with the following events:

Event 'response' #
function (response) { }

Emitted when a response is received to this request. This event is emitted only once. The response argument
will be an instance of http.ClientResponse .

request.write(chunk, encoding='utf8') #
Sends a chunk of the body. By calling this method many times, the user can stream a request body to a server--in
that case it is suggested to use the ['Transfer-Encoding', 'chunked'] header line when creating the
request.

The chunk argument should be an array of integers or a string.

The encoding argument is optional and only applies when chunk is a string.

request.end([data], [encoding]) #
Finishes sending the request. If any parts of the body are unsent, it will flush them to the stream. If the request is
chunked, this will send the terminating '0\r\n\r\n' .

If data is specified, it is equivalent to calling request.write(data, encoding) followed by


request.end() .

request.abort() #
Aborts a request. (New since v0.3.8.)

http.ClientResponse #
This object is created when making a request with http.request() . It is passed to the 'response' event of
the request object.

The response implements the Readable Stream interface.

http://nodejs-es.github.io/api/all.html 88/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

Event: 'data' #
function (chunk) {}

Emitted when a piece of the message body is received.

Event: 'end' #
function () {}

Emitted exactly once for each message. No arguments. After emitted no other events will be emitted on the
response.

response.statusCode #
The 3-digit HTTP response status code. E.G. 404 .

response.httpVersion #
The HTTP version of the connected-to server. Probably either '1.1' or '1.0' . Also
response.httpVersionMajor is the first integer and response.httpVersionMinor is the second.

response.headers #
The response headers object.

response.trailers #
The response trailers object. Only populated after the 'end' event.

response.setEncoding(encoding=null) #
Set the encoding for the response body. Either 'utf8' , 'ascii' , or 'base64' . Defaults to null , which
means that the 'data' event will emit a Buffer object..

response.pause() #
Pauses response from emitting events. Useful to throttle back a download.

response.resume() #
Resumes a paused response.

HTTPS #

Stability: 3 - Stable

http://nodejs-es.github.io/api/all.html 89/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

HTTPS es el protocolo HTTP sobre TLS/SSL. En Node se implementa en un módulo separado.

Class: https.Server #
This class is a subclass of tls.Server and emits events same as http.Server . See http.Server for more
information.

https.createServer(options, [requestListener]) #
Returns a new HTTPS web server object. The options is similar to tls.createServer(). The requestListener
is a function which is automatically added to the 'request' event.

Ejemplo:

// curl -k https://localhost:8000/
var https = require('https');
var fs = require('fs');

var options = {
key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem')
};

https.createServer(options, function (req, res) {


res.writeHead(200);
res.end("hola mundo\n");
}).listen(8000);

https.request(options, callback) #
Hace una petición a un servidor web seguro. Opciones similares a http.request() .

Ejemplo:

var https = require('https');

var options = {
host: 'encrypted.google.com',
port: 443,
path: '/',
method: 'GET'
};

var req = https.request(options, function(res) {


console.log("statusCode: ", res.statusCode);
console.log("headers: ", res.headers);

res.on('data', function(d) {
process.stdout.write(d);
});
});
req.end();

req.on('error', function(e) {
console.error(e);

http://nodejs-es.github.io/api/all.html 90/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

});

El argumento options tiene las siguientes opciones

host: IP o dominio del host al que hacer la petición. Por defecto 'localhost'.
port: puerto del host al que hacer la petición. Por defecto 443.
path: Ruta de la petición. Por defecto '/'.
method: Método de la petición HTTP. Per defecto 'GET' .
host : A domain name or IP address of the server to issue the request to. Defaults to 'localhost' .
hostname: To support url.parse() hostname is preferred over host
port: Port of remote server. Defaults to 443.
method: A string specifying the HTTP request method. Defaults to 'GET'.
path: Request path. Defaults to '/'. Should include query string if any. E.G. '/index.html?page=12'
headers: An object containing request headers.
auth: Basic authentication i.e. 'user:password' to compute an Authorization header.
agent: Controls Agent behavior. When an Agent is used request will default to Connection: keep-alive.
Possible values:
undefined (default): use globalAgent for this host and port.
Agent object: explicitly use the passed in Agent.
false: opts out of connection pooling with an Agent, defaults request to Connection: close.

The following options from tls.connect() can also be specified. However, a globalAgent silently ignores these.

key: Clave privada a usar para SSL. Por defecto null.


passphrase: A string of passphrase for the private key. Default null.
cert: Certificado público x509 a usar. Por defecto null.
ca: Un certificado de autoridad o un array de certificados de autoridad para comprobar contra el host
remoto.
ciphers: A string describing the ciphers to use or exclude. Consult
http://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT for details on the format.
rejectUnauthorized: If true, the server certificate is verified against the list of supplied CAs. An
'error' event is emitted if verification fails. Verification happens at the connection level, before the HTTP
request is sent. Default false.

In order to specify these options, use a custom Agent .

Example:

var options = {
host: 'encrypted.google.com',
port: 443,
path: '/',
method: 'GET',
key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem')
};
options.agent = new https.Agent(options);

var req = https.request(options, function(res) {


...
}

Or does not use an Agent .

Example:
http://nodejs-es.github.io/api/all.html 91/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

var options = {
host: 'encrypted.google.com',
port: 443,
path: '/',
method: 'GET',
key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'),
agent: false
};

var req = https.request(options, function(res) {


...
}

https.get(options, callback) #
Con http.get() pero para HTTPS.

Ejemplo:

var https = require('https');

https.get({ host: 'encrypted.google.com', path: '/' }, function(res) {


console.log("statusCode: ", res.statusCode);
console.log("headers: ", res.headers);

res.on('data', function(d) {
process.stdout.write(d);
});

}).on('error', function(e) {
console.error(e);
});

Class: https.Agent #
An Agent object for HTTPS similar to http.Agent. See https.request() for more information.

https.globalAgent #
Global instance of https.Agent which is used as the default for all HTTPS client requests.

URL #
Este módulo posee utilidades para la resolución y análisis de URL. Para usarlo utilice require('url') .

Analizar objetos URL tiene algo o mucho de los siguientes campos, dependiendo de que exista o no en la cadena
de URL. Las partes que no están en la cadena de URL no se analizarán y no estarán presente en el objeto. Un
ejemplo para la siguiente URL

'http://user:pass@host.com:8080/p/a/t/h?query=string#hash'

http://nodejs-es.github.io/api/all.html 92/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

href : La dirección URL ha sido analizada desde un principio.


Ejemplo: 'http://user:pass@host.com:8080/p/a/t/h?query=string#hash'

protocol : El protocolo de petición (request).


Ejemplo: 'http:'

host : Una parte del host de la URL completa, incluyendo la información del puerto y autentificación.
Ejemplo: 'user:pass@host.com:8080'

auth : Parte de la información de autentificación de la URL.


Ejemplo: 'user:pass'

hostname : Sólo la parte del nombre del host.


Ejemplo: 'host.com'

port : El número de puerto del host.


Ejemplo: '8080'

pathname : La sección de la ruta de la URL, que viene después del host y antes de la consulta, incluyendo la
barra inicial si está presente.
Ejemplo: '/p/a/t/h'

search : La parte de 'cadena de consulta' de la URL, incluyendo el signo de interrogación principal.


Ejemplo: '?query=string'

query : La parte de cualquier 'parámetro' de la cadena de consulta, o un parser de un objeto de cadena de


consulta.
Ejemplo: 'query=string' o {'query':'string'}

hash : La parte del 'fragmento' de la URL incluyendo el símbolo de la libra.


Ejemplo: '#hash'

Los siguientes métodos son proporcionados por el módulo URL:

url.parse(urlStr, [parseQueryString], [slashesDenoteHost]) #


Toma una cadena de la URL, y la devuelve como un objeto. Devuelve true como el segundo argumento a la
cadena de consulta usando el módulo querystring .

url.format(urlObj) #
Toma un parser de un objeto URL, y devuelve una cadena de URL.

url.resolve(from, to) #
Toma una URL base, y el atributo href de la URL, y lo determina como un navegador sería la etiqueta anchor
(enlace).

Cadena de consulta #
Este módulo provee de utilidades para el tratamiento de cadenas de consultas. Se ofrece los siguientes métodos:

http://nodejs-es.github.io/api/all.html 93/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

querystring.stringify(obj, sep='&', eq='=') #


Serializa un objeto a una cadena de consulta. Opcionalmente reemplaza el separador por omisión y la asignación
de caracteres.

Ejemplo:

querystring.stringify({foo: 'bar'})
// devuelve
'foo=bar'

querystring.stringify({foo: 'bar', baz: 'bob'}, ';', ':')


// devuelve
'foo:bar;baz:bob'

querystring.parse(str, sep='&', eq='=') #


Deserializa una cadena de consulta a un objeto. Opcionamente puede reemplazar el separador por omisión y
asignar caracteres.

Ejemplo:

querystring.parse('a=b&b=c')
// returns
{ a: 'b', b: 'c' }

querystring.escape #
La función escape es usada por querystring.stringify , para proporcionar reemplazos si es necesario.

querystring.unescape #
La función unescape es usada por querystring.parse , para proporcionar reemplazos si es necesario.

Readline #

Stability: 3 - Stable

This module allows reading of a stream (such as STDIN) on a line-by-line basis.

Note that once you've invoked this module, your node program will not terminate until you've closed the
interface, and the STDIN stream. Here's how to allow your program to gracefully terminate:

var readline = require('readline');

var i = readline.createInterface(process.sdtin, process.stdout, null);


i.question("What do you think of node.js?", function(answer) {
//TODO: Log the answer in a database
console.log("Thank you for your valuable feedback.");
i.close(); //These two lines together allow the program to
process.stdin.destroy(); //terminate. Without them, it would run forever.

http://nodejs-es.github.io/api/all.html 94/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

});

createInterface(input, output, completer) #


Returns an interface object, which reads from input, and writes to output. TODO: I think "completer" is used for
tab-completion, but not sure.

interface.setPrompt(prompt, length) #
TODO

interface.prompt() #
TODO: Appears to trigger showing the prompt.

interface.question(query, cb) #
Displays the query to the user, and then calls the callback after the user has typed in their response.

Example usage:

interface.question("What is your favorite food?", function(answer) {


console.log("Oh, so your favorite food is " + answer);
});

interface.close() #
TODO

interface.pause() #
TODO

interface.resume() #
TODO

interface.write() #
TODO

REPL #
Read-Eval-Print-Loop (REPL) está disponible como un programa independiente y fácilmente puede incluirse en
otros programas. REPL proporciona una forma interactiva de ejecutar JavaScript y ver los resultados. Puede ser
utilizado para la depuración, pruebas, o simplemente para probar cosas.

Debe ejectuarlo en node sin singún argumento desde la línea de comandos, debe posicionarse dentro de REPL.
Posee la edición simple de líneas de emacs.
http://nodejs-es.github.io/api/all.html 95/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

mjr:~$ node
Type '.help' for options.
> a = [ 1, 2, 3];
[ 1, 2, 3 ]
> a.forEach(function (v) {
... console.log(v);
... });
1
2
3

Para editores avanzados, inice node con la variable de entorno NODE_NO_READLINE=1 . Se iniciará la
configuración de REPL en la terminal y l permite utilizarlo con rlwrap .

Por ejemplo, puede añadir lo siguiente al fichero bashrc:

alias node="env NODE_NO_READLINE=1 rlwrap node"

repl.start([prompt], [stream], [eval], [useGlobal], #


[ignoreUndefined])
Inicia REPL con el prompt como el prompt y el stream para todo los procesos de I/O (Entrada/Salida).
prompt es opcional y por omisión es > . stream es opcional y por omisión es process.stdin . eval is
optional too and defaults to async wrapper for eval() .

If useGlobal is set to true, then the repl will use the global object, instead of running scripts in a separate
context. Defaults to false .

If ignoreUndefined is set to true, then the repl will not output return value of command if it's undefined .
Defaults to false .

You can use your own eval function if it has following signature:

function eval(cmd, callback) {


callback(null, result);
}

Multiples REPLs pueden iniciar con una misma instancia de node. Cada uno de ellos comparten el objeto global,
pero tendrán un único proceso de I/O.

Acontinuación un ejemplo que inicia REPL en stdin, un socket en Unix, y un socket en TCP:

var net = require("net"),


repl = require("repl");

connections = 0;

repl.start("node via stdin> ");

net.createServer(function (socket) {
connections += 1;
repl.start("node via Unix socket> ", socket);
}).listen("/tmp/node-repl-sock");

http://nodejs-es.github.io/api/all.html 96/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

net.createServer(function (socket) {
connections += 1;
repl.start("node via TCP socket> ", socket);
}).listen(5001);

Ejecutando el programa desde la línea de comando iniciará REPL en stdin. Otros clientes REPL pueden
conectarse a través de un socket Unix o TCP. telnet es útil para la conexión de sockets TCP, y socat puede
ser conectar ambos sockets Unix y TCP.

Al iniciar REPL desde un socket Unix basado en una instancia de stdin, puede conectarse a un proceso en
ejecución de node sin reiniciar el mismo.

Características de REPL #
Dentro de REPL, presione Control+D para salir. Expresiones de varias líneas pueden ser ingresadas.

La variable especial _ (underscore) contiene el resultado de la última expresión.

> [ "a", "b", "c" ]


[ 'a', 'b', 'c' ]
> _.length
3
> _ += 1
4

REPL proporciona acceso a cualquier variable de ámbito global. Puede exponer una variable a REPL
explícitamente y asignarle a un contexto de objeto asociado con cada REPLServer . Por ejemplo:

// repl_test.js
var repl = require("repl"),
msg = "message";

repl.start().context.m = msg;

Los sucesos en el objeto context aparecen como local en REPL:

mjr:~$ node repl_test.js


> m
'message'

Hay algunos comandos especiales de REPL:

.break - Si bien ingresar expresiones en varias líneas, a veces, pueden perderse o simplemente no son
tomados en cuenta. .break comenzará de nuevo.
.clear - Restablece el objeto context a un objeto vacío y borra cualquier expresión de varias líneas.
.exit - Cierra los stream de I/O, que hará que REPL termine.
.help - Muestra la lista de comandos especiales.
.save - Guarda la sesión actual de REPL en un fichero

.save ./file/to/save.js

.load - Carga un fichero en la sesión actual de REPL.

.load ./file/to/load.js

Lo siguiente son combinaciones del teclado para el uso especial de REPL:


http://nodejs-es.github.io/api/all.html 97/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

<ctrl>C - Similar a la tecla break. Termina el comando actual. Presione dos veces en la línea para forzar la
salida.
<ctrl>D - Similar a la tecla .exit.

Executing JavaScript #

Stability: 3 - Stable

You can access this module with:

var vm = require('vm');

JavaScript code can be compiled and run immediately or compiled, saved, and run later.

vm.runInThisContext(code, [filename]) #
vm.runInThisContext() compiles code , runs it and returns the result. Running code does not have access to
local scope. filename is optional, it's used only in stack traces.

Example of using vm.runInThisContext and eval to run the same code:

var localVar = 123,


usingscript, evaled,
vm = require('vm');

usingscript = vm.runInThisContext('localVar = 1;',


'myfile.vm');
console.log('localVar: ' + localVar + ', usingscript: ' +
usingscript);
evaled = eval('localVar = 1;');
console.log('localVar: ' + localVar + ', evaled: ' +
evaled);

// localVar: 123, usingscript: 1


// localVar: 1, evaled: 1

vm.runInThisContext does not have access to the local scope, so localVar is unchanged. eval does have
access to the local scope, so localVar is changed.

In case of syntax error in code , vm.runInThisContext emits the syntax error to stderr and throws an
exception.

vm.runInNewContext(code, [sandbox], [filename]) #


vm.runInNewContext compiles code , then runs it in sandbox and returns the result. Running code does not
have access to local scope. The object sandbox will be used as the global object for code . sandbox and
filename are optional, filename is only used in stack traces.

Example: compile and execute code that increments a global variable and sets a new one. These globals are
contained in the sandbox.

var util = require('util'),

http://nodejs-es.github.io/api/all.html 98/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

vm = require('vm'),
sandbox = {
animal: 'cat',
count: 2
};

vm.runInNewContext('count += 1; name = "kitty"', sandbox, 'myfile.vm');


console.log(util.inspect(sandbox));

// { animal: 'cat', count: 3, name: 'kitty' }

Note that running untrusted code is a tricky business requiring great care. To prevent accidental global variable
leakage, vm.runInNewContext is quite useful, but safely running untrusted code requires a separate process.

In case of syntax error in code , vm.runInNewContext emits the syntax error to stderr and throws an
exception.

vm.runInContext(code, context, [filename]) #


vm.runInContext compiles code , then runs it in context and returns the result. A (V8) context comprises a
global object, together with a set of built-in objects and functions. Running code does not have access to local
scope and the global object held within context will be used as the global object for code . filename is
optional, it's used only in stack traces.

Example: compile and execute code in a existing context.

var util = require('util'),


vm = require('vm'),
initSandbox = {
animal: 'cat',
count: 2
},
context = vm.createContext(initSandbox);

vm.runInContext('count += 1; name = "CATT"', context, 'myfile.vm');


console.log(util.inspect(context));

// { animal: 'cat', count: 3, name: 'CATT' }

Note that createContext will perform a shallow clone of the supplied sandbox object in order to initialise the
global object of the freshly constructed context.

Note that running untrusted code is a tricky business requiring great care. To prevent accidental global variable
leakage, vm.runInContext is quite useful, but safely running untrusted code requires a separate process.

In case of syntax error in code , vm.runInContext emits the syntax error to stderr and throws an exception.

vm.createContext([initSandbox]) #
vm.createContext creates a new context which is suitable for use as the 2nd argument of a subsequent call to
vm.runInContext . A (V8) context comprises a global object together with a set of build-in objects and
functions. The optional argument initSandbox will be shallow-copied to seed the initial contents of the global
object used by the context.

vm.createScript(code, [filename]) #
http://nodejs-es.github.io/api/all.html 99/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

createScript compiles code but does not run it. Instead, it returns a vm.Script object representing this
compiled code. This script can be run later many times using methods below. The returned script is not bound to
any global object. It is bound before each run, just for that run. filename is optional, it's only used in stack
traces.

In case of syntax error in code , createScript prints the syntax error to stderr and throws an exception.

Class: Script #
A class for running scripts. Returned by vm.createScript.

script.runInThisContext() #
Similar to vm.runInThisContext but a method of a precompiled Script object.
script.runInThisContext runs the code of script and returns the result. Running code does not have
access to local scope, but does have access to the global object (v8: in actual context).

Example of using script.runInThisContext to compile code once and run it multiple times:

var vm = require('vm');

globalVar = 0;

var script = vm.createScript('globalVar += 1', 'myfile.vm');

for (var i = 0; i < 1000 ; i += 1) {


script.runInThisContext();
}

console.log(globalVar);

// 1000

script.runInNewContext([sandbox]) #
Similar to vm.runInNewContext a method of a precompiled Script object. script.runInNewContext runs
the code of script with sandbox as the global object and returns the result. Running code does not have
access to local scope. sandbox is optional.

Example: compile code that increments a global variable and sets one, then execute this code multiple times.
These globals are contained in the sandbox.

var util = require('util'),


vm = require('vm'),
sandbox = {
animal: 'cat',
count: 2
};

var script = vm.createScript('count += 1; name = "kitty"', 'myfile.vm');

for (var i = 0; i < 10 ; i += 1) {


script.runInNewContext(sandbox);
}
http://nodejs-es.github.io/api/all.html 100/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

console.log(util.inspect(sandbox));

// { animal: 'cat', count: 12, name: 'kitty' }

Note that running untrusted code is a tricky business requiring great care. To prevent accidental global variable
leakage, script.runInNewContext is quite useful, but safely running untrusted code requires a separate
process.

Child Process #

Stability: 3 - Stable

Node proporciona un popen(3) tri-direccional a través del módulo ChildProcess .

Es posible pasar un stream de datos a través del stdin , stdout , y stderr del proceso hijo (child) de manera
totalmente sin bloqueo.

Para crear un proceso hijo utilice require('child_process').spawn() o


require('child_process').fork() . La semántica de cada uno son un poco diferente, y se explica a
continuación.

Class: ChildProcess #
ChildProcess es EventEmitter .

Los procesos hijo siempre tienen tres streams asociados a ellos. child.stdin , child.stdout , y
child.stderr . These may be shared with the stdio streams of the parent process, or they may be separate
stream objects which can be piped to and from.

The ChildProcess class is not intended to be used directly. Use the spawn() or fork() methods to create a
Child Process instance.

Evento: 'exit' #
code Number the exit code, if it exited normally.
signal String the signal passed to kill the child process, if it was killed by the parent.

Este evento es emitido después de termine el proceso hijo. Si el proceso terminó de manera normal, code es el
código de salida final, en caso contrario null . Si el proceso terminó debido al recibo de una señal, signal es el
nombre string de la señal, en caso contrario null .

Véase waitpid(2) .

Event: 'disconnect' #
This event is emitted after using the .disconnect() method in the parent or in the child. After disconnecting it
is no longer possible to send messages. An alternative way to check if you can send messages is to see if the
child.connected property is true .

http://nodejs-es.github.io/api/all.html 101/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

child.stdin #
Stream object

Un Stream de Escritura que representa el stdin del proceso hijo. Cerrar este stream vía end() a menudo
causa que termine el proceso hijo.

If the child stdio streams are shared with the parent, then this will not be set.

child.stdout #
Stream object

Un Stream de Lectura que representa el stdout del proceso hijo.

If the child stdio streams are shared with the parent, then this will not be set.

child.stderr #
Stream object

Un Stream de Lectura que representa el stderr del proceso hijo.

If the child stdio streams are shared with the parent, then this will not be set.

child.pid #
Integer

El PID del proceso hijo.

Ejemplo:

var spawn = require('child_process').spawn,


grep = spawn('grep', ['ssh']);

console.log('Spawned child pid: ' + grep.pid);


grep.stdin.end();

child.kill([signal]) #
signal String

Manda una señal al proceso hijo. Si ningún argumento es dado, el proceso enviará 'SIGTERM' . Véase
signal(7) para una lista de señales disponibles.

var spawn = require('child_process').spawn,


grep = spawn('grep', ['ssh']);

grep.on('exit', function (code, signal) {


console.log('child process terminated due to receipt of signal '+signal);
});

http://nodejs-es.github.io/api/all.html 102/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

// send SIGHUP to process


grep.kill('SIGHUP');

Observa que mientras la función se llama kill , la señal entregada al proceso hijo puede o no terminarlo. kill
realmente solo manda una señal a un proceso.

Véase kill(2)

child.send(message, [sendHandle]) #
message Object
sendHandle Handle object

Send a message (and, optionally, a handle object) to a child process.

See child_process.fork() for details.

child_process.spawn(command, [args], [options]) #


command String The command to run
args Array List of string arguments
options Object
cwd String Current working directory of the child process
customFds Array Deprecated File descriptors for the child to use for stdio. (See below)
env Object Environment key-value pairs
setsid Boolean
return: ChildProcess object

Inicia un nuevo proceso con el command proporcionado, con argumentos de linea de comandos args . Si es
omitido, args por defecto sera un Array vacío.

El tercer argumento es usado para especificar opciones adicionales, que por defecto serán:

{ cwd: undefined,
env: process.env
}

cwd te deja especificar el directorio actual de trabajo del cual es iniciado el proceso. Usa env para especificar
variables de entorno que serán visibles al nuevo proceso.

Ejemplo ejecutando ls -lh /usr , capturando stdout , stderr , y el codigo de salida:

var util = require('util'),


spawn = require('child_process').spawn,
ls = spawn('ls', ['-lh', '/usr']);

ls.stdout.on('data', function (data) {


console.log('stdout: ' + data);
});

ls.stderr.on('data', function (data) {


console.log('stderr: ' + data);
});

ls.on('exit', function (code) {


http://nodejs-es.github.io/api/all.html 103/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

console.log('child process exited with code ' + code);


});

Ejemplo: Una manera muy elaborada de ejecutar 'ps ax | grep ssh'

var util = require('util'),


spawn = require('child_process').spawn,
ps = spawn('ps', ['ax']),
grep = spawn('grep', ['ssh']);

ps.stdout.on('data', function (data) {


grep.stdin.write(data);
});

ps.stderr.on('data', function (data) {


console.log('ps stderr: ' + data);
});

ps.on('exit', function (code) {


if (code !== 0) {
console.log('ps process exited with code ' + code);
}
grep.stdin.end();
});

grep.stdout.on('data', function (data) {


console.log(data);
});

grep.stderr.on('data', function (data) {


console.log('grep stderr: ' + data);
});

grep.on('exit', function (code) {


if (code !== 0) {
console.log('grep process exited with code ' + code);
}
});

Ejemplo de comprobar por ejecución fallida:

var spawn = require('child_process').spawn,


child = spawn('bad_command');

child.stderr.setEncoding('utf8');
child.stderr.on('data', function (data) {
if (/^execvp\(\)/.test(data)) {
console.log('Failed to start child process.');
}
});

Note that if spawn receives an empty options object, it will result in spawning the process with an empty
environment rather than using process.env . This due to backwards compatibility issues with a deprecated
API.

There is a deprecated option called customFds which allows one to specify specific file descriptors for the stdio
of the child process. This API was not portable to all platforms and therefore removed. With customFds it was
http://nodejs-es.github.io/api/all.html 104/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

possible to hook up the new process' [stdin, stdout, stderr] to existing streams; -1 meant that a new
stream should be created. Use at your own risk.

There are several internal options. In particular stdinStream , stdoutStream , stderrStream . They are for
INTERNAL USE ONLY. As with all undocumented APIs in Node, they should not be used.

Véase tambien: child_process.exec() y child_process.fork()

child_process.exec(command, [options], callback) #


command String The command to run, with space-separated arguments
options Object
cwd String Current working directory of the child process
customFds Array Deprecated File descriptors for the child to use for stdio. (See below)
env Object Environment key-value pairs
setsid Boolean
encoding String (Default: 'utf8')
timeout Number (Default: 0)
maxBuffer Number (Default: 200*1024)
killSignal String (Default: 'SIGTERM')
callback Function called with the output when process terminates
code Integer Exit code
stdout Buffer
stderr Buffer
Return: ChildProcess object

Runs a command in a shell and buffers the output.

var util = require('util'),


exec = require('child_process').exec,
child;

child = exec('cat *.js bad_file | wc -l',


function (error, stdout, stderr) {
console.log('stdout: ' + stdout);
console.log('stderr: ' + stderr);
if (error !== null) {
console.log('exec error: ' + error);
}
});

El callback recibe los argumentos (error, stdout, stderr) . Cuando termina con éxito, error sera null .
Cuando termina con error, error sera una instancia de Error y err.code sera el código de salida del
proceso hijo, y err.signal sera la señal que terminó el proceso.

Hay un segundo argumento opcional para especificar varias opciones. Las opciones predeterminadas son

{ encoding: 'utf8',
timeout: 0,
maxBuffer: 200*1024,
killSignal: 'SIGTERM',
cwd: null,
env: null }

Si timeout es mayor que 0, entonces detendrá el proceso hijo si este se ejecuta mas de timeout milisegundos.
El proceso hijo se detiene con killSignal (por defecto: 'SIGTERM' ). maxBuffer especifica la mayor
http://nodejs-es.github.io/api/all.html 105/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

cantidad de datos permitidos en stdout o stderr - si este valor se excede el proceso hijo sera terminado.

child_process.execFile(file, args, options, callback) #


file String The filename of the program to run
args Array List of string arguments
options Object
cwd String Current working directory of the child process
customFds Array Deprecated File descriptors for the child to use for stdio. (See below)
env Object Environment key-value pairs
setsid Boolean
encoding String (Default: 'utf8')
timeout Number (Default: 0)
maxBuffer Number (Default: 200*1024)
killSignal String (Default: 'SIGTERM')
callback Function called with the output when process terminates
code Integer Exit code
stdout Buffer
stderr Buffer
Return: ChildProcess object

This is similar to child_process.exec() except it does not execute a subshell but rather the specified file
directly. This makes it slightly leaner than child_process.exec . It has the same options.

child_process.fork(modulePath, [args], [options]) #


modulePath String The module to run in the child
args Array List of string arguments
options Object
cwd String Current working directory of the child process
customFds Array Deprecated File descriptors for the child to use for stdio. (See below)
env Object Environment key-value pairs
setsid Boolean
encoding String (Default: 'utf8')
timeout Number (Default: 0)
callback Function called with the output when process terminates
code Integer Exit code
stdout Buffer
stderr Buffer
Return: ChildProcess object

This is a special case of the spawn() functionality for spawning Node processes. In addition to having all the
methods in a normal ChildProcess instance, the returned object has a communication channel built-in. The
channel is written to with child.send(message, [sendHandle]) and messages are received by a
'message' event on the child.

For example:

var cp = require('child_process');

var n = cp.fork(__dirname + '/sub.js');

n.on('message', function(m) {
console.log('PARENT got message:', m);
});

http://nodejs-es.github.io/api/all.html 106/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

n.send({ hello: 'world' });

And then the child script, 'sub.js' might look like this:

process.on('message', function(m) {
console.log('CHILD got message:', m);
});

process.send({ foo: 'bar' });

In the child the process object will have a send() method, and process will emit objects each time it
receives a message on its channel.

There is a special case when sending a {cmd: 'NODE_foo'} message. All messages containing a NODE_ prefix
in its cmd property will not be emitted in the message event, since they are internal messages used by node
core. Messages containing the prefix are emitted in the internalMessage event, you should by all means avoid
using this feature, it may change without warranty.

By default the spawned Node process will have the stdout, stderr associated with the parent's. To change this
behavior set the silent property in the options object to true .

These child Nodes are still whole new instances of V8. Assume at least 30ms startup and 10mb memory for each
new Node. That is, you cannot create many thousands of them.

The sendHandle option to child.send() is for sending a handle object to another process. Child will receive
the handle as as second argument to the message event. Here is an example of sending a handle:

var server = require('net').createServer();


var child = require('child_process').fork(__dirname + '/child.js');
// Open up the server object and send the handle.
server.listen(1337, function() {
child.send({ server: true }, server._handle);
});

Here is an example of receiving the server handle and sharing it between processes:

process.on('message', function(m, serverHandle) {


if (serverHandle) {
var server = require('net').createServer();
server.listen(serverHandle);
}
});

To close the IPC connection between parent and child use the child.disconnect() method. This allows the
child to exit gracefully since there is no IPC channel keeping it alive. When calling this method the disconnect
event will be emitted in both parent and child, and the connected flag will be set to false . Please note that
you can also call process.disconnect() in the child process.

Assert #
Este módulo es usado para escribir pruebas unitarias de sus aplicaciones, puede acceder con
require('assert') .

http://nodejs-es.github.io/api/all.html 107/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

assert.fail(actual, expected, message, operator) #


Evalua si actual es igual a expected usando el operador provisto.

assert.ok(value, [message]) #
Evalua si el valor es true , si es equivalente a assert.equal(true, value, message);

assert.equal(actual, expected, [message]) #


Evalua la igualdad con el operador de comparación ( == ).

assert.notEqual(actual, expected, [message]) #


Evalua la no igualdad con el operador de comparación en negación ( != ).

assert.deepEqual(actual, expected, [message]) #


Pruebas para las pruebas de afirmación de desigualdad profunda.

assert.notDeepEqual(actual, expected, [message]) #


Pruebas para cualquier desigualdad profunda.

assert.strictEqual(actual, expected, [message]) #


Pruebas de igualdad estrictas, según lo determinado por el operador de igualdad estricto ( === )

assert.notStrictEqual(actual, expected, [message]) #


Pruebas de no igualdad estrictas, según lo determinado por el operador de no igualdad estricto ( !== )

assert.throws(block, [error], [message]) #


Se espera lanzar un bloque (block) de error. El error puede ser un constructor, expresión regular (regexp) o
una función de validación.

Validar instanceof usando el constructor:

assert.throws(
function() {
throw new Error("Wrong value");
},
Error
);

Validar un mensaje de error usando RegExp:

assert.throws(
function() {
throw new Error("Wrong value");
},

http://nodejs-es.github.io/api/all.html 108/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

/value/
);

Error de validación personalizado:

assert.throws(
function() {
throw new Error("Wrong value");
},
function(err) {
if ( (err instanceof Error) && /value/.test(err) ) {
return true;
}
},
"unexpected error"
);

assert.doesNotThrow(block, [error], [message]) #


Se espera un bloque (block) y no produzca un error, vea assert.throws para más detalles.

assert.ifError(value) #
Comprueba si el valor no es falso, se produce un lanzamiento si el valor es verdadero. Muy útil cuando se prueba
el primer argumento, error en los callbacks.

TTY (Terminal) #
Utilice require('tty') para acceder al módulo.

Ejemplo:

var tty = require('tty');


tty.setRawMode(true);
process.stdin.resume();
process.stdin.on('keypress', function(char, key) {
if (key && key.ctrl && key.name == 'c') {
console.log('salida airosa');
process.exit()
}
});

tty.open(path, args=[]) #
Genera un nuevo proceso con el fichero ejecutable en la ruta como la sesión actual a una nueva pseudo
terminal.

Devuelve un array [slaveFD, childProcess] . slaveFD es el descriptor de fichero esclavo de la pseudo


terminal. childProcess es un proceso hijo de un objeto.

tty.isatty(fd) #
http://nodejs-es.github.io/api/all.html 109/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

Devuelve true o false dependiendo si el fd es asociado con el terminal.

tty.setRawMode(mode) #
mode debe ser true o false . Se establece las propiedades al proceso actual de stdin fd para actuar ya sea
como un dispositivo de modo sin formato o por omisión.

tty.setWindowSize(fd, row, col) #


ioctl ajusta la configuración de la ventana del descriptor de fichero.

tty.getWindowSize(fd) #
Devuelve [row, col] associado a la TTY con el descriptor de fichero.

Zlib #

Stability: 3 - Stable

You can access this module with:

var zlib = require('zlib');

This provides bindings to Gzip/Gunzip, Deflate/Inflate, and DeflateRaw/InflateRaw classes. Each class takes the
same options, and is a readable/writable Stream.

Examples #
Compressing or decompressing a file can be done by piping an fs.ReadStream into a zlib stream, then into an
fs.WriteStream.

var gzip = zlib.createGzip();


var fs = require('fs');
var inp = fs.createReadStream('input.txt');
var out = fs.createWriteStream('input.txt.gz');

inp.pipe(gzip).pipe(out);

Compressing or decompressing data in one step can be done by using the convenience methods.

var input = '.................................';


zlib.deflate(input, function(err, buffer) {
if (!err) {
console.log(buffer.toString('base64'));
}
});

var buffer = new Buffer('eJzT0yMAAGTvBe8=', 'base64');


zlib.unzip(buffer, function(err, buffer) {
if (!err) {
console.log(buffer.toString());

http://nodejs-es.github.io/api/all.html 110/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

}
});

To use this module in an HTTP client or server, use the accept-encoding on requests, and the content-encoding
header on responses.

Note: these examples are drastically simplified to show the basic concept. Zlib encoding can be


expensive, and the results ought to be cached. See Memory Usage Tuning below for more information on the
speed/memory/compression tradeoffs involved in zlib usage.

// client request example


var zlib = require('zlib');
var http = require('http');
var fs = require('fs');
var request = http.get({ host: 'izs.me',
path: '/',
port: 80,
headers: { 'accept-encoding': 'gzip,deflate' } });
request.on('response', function(response) {
var output = fs.createWriteStream('izs.me_index.html');

switch (response.headers['content-encoding']) {
// or, just use zlib.createUnzip() to handle both cases
case 'gzip':
response.pipe(zlib.createGunzip()).pipe(output);
break;
case 'deflate':
response.pipe(zlib.createInflate()).pipe(output);
break;
default:
response.pipe(output);
break;
}
});

// server example
// Running a gzip operation on every request is quite expensive.
// It would be much more efficient to cache the compressed buffer.
var zlib = require('zlib');
var http = require('http');
var fs = require('fs');
http.createServer(function(request, response) {
var raw = fs.createReadStream('index.html');
var acceptEncoding = request.headers['accept-encoding'];
if (!acceptEncoding) {
acceptEncoding = '';
}

// Note: this is not a conformant accept-encoding parser.


// See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.3
if (acceptEncoding.match(/\bdeflate\b/)) {
response.writeHead(200, { 'content-encoding': 'deflate' });
raw.pipe(zlib.createDeflate()).pipe(response);
} else if (acceptEncoding.match(/\bgzip\b/)) {
response.writeHead(200, { 'content-encoding': 'gzip' });
raw.pipe(zlib.createGzip()).pipe(response);
} else {
response.writeHead(200, {});

http://nodejs-es.github.io/api/all.html 111/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

raw.pipe(response);
}
}).listen(1337);

Constants #
All of the constants defined in zlib.h are also defined on require('zlib') . They are described in more detail in
the zlib documentation. See http://zlib.net/manual.html#Constants for more details.

zlib.createGzip([options]) #
Returns a new Gzip object with an options.

zlib.createGunzip([options]) #
Returns a new Gunzip object with an options.

zlib.createDeflate([options]) #
Returns a new Deflate object with an options.

zlib.createInflate([options]) #
Returns a new Inflate object with an options.

zlib.createDeflateRaw([options]) #
Returns a new DeflateRaw object with an options.

zlib.createInflateRaw([options]) #
Returns a new InflateRaw object with an options.

zlib.createUnzip([options]) #
Returns a new Unzip object with an options.

Class: zlib.Gzip #
Compress data using gzip.

Class: zlib.Gunzip #
Decompress a gzip stream.

Class: zlib.Deflate #
Compress data using deflate.

Class: zlib.Inflate
http://nodejs-es.github.io/api/all.html 112/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

Decompress a deflate stream. #

Class: zlib.DeflateRaw #
Compress data using deflate, and do not append a zlib header.

Class: zlib.InflateRaw #
Decompress a raw deflate stream.

Class: zlib.Unzip #
Decompress either a Gzip- or Deflate-compressed stream by auto-detecting the header.

Convenience Methods #
All of these take a string or buffer as the first argument, and call the supplied callback with callback(error,
result) . The compression/decompression engine is created using the default settings in all convenience
methods. To supply different options, use the zlib classes directly.

zlib.deflate(buf, callback) #
Compress a string with Deflate.

zlib.deflateRaw(buf, callback) #
Compress a string with DeflateRaw.

zlib.gzip(buf, callback) #
Compress a string with Gzip.

zlib.gunzip(buf, callback) #
Decompress a raw Buffer with Gunzip.

zlib.inflate(buf, callback) #
Decompress a raw Buffer with Inflate.

zlib.inflateRaw(buf, callback) #
Decompress a raw Buffer with InflateRaw.

zlib.unzip(buf, callback) #
Decompress a raw Buffer with Unzip.

Options #
Each class takes an options object. All options are optional. (The convenience methods use the default settings
http://nodejs-es.github.io/api/all.html 113/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

for all options.)

Note that some options are only relevant when compressing, and are ignored by the decompression classes.

chunkSize (default: 16*1024)


windowBits
level (compression only)
memLevel (compression only)
strategy (compression only)
dictionary (deflate/inflate only, empty dictionary by default)

See the description of deflateInit2 and inflateInit2 at

http://zlib.net/manual.html#Advanced for more information on these.

Memory Usage Tuning #


From zlib/zconf.h , modified to node's usage:

The memory requirements for deflate are (in bytes):

(1 << (windowBits+2)) + (1 << (memLevel+9))

that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values) plus a few kilobytes for small objects.

For example, if you want to reduce the default memory requirements from 256K to 128K, set the options to:

{ windowBits: 14, memLevel: 7 }

Of course this will generally degrade compression (there's no free lunch).

The memory requirements for inflate are (in bytes)

1 << windowBits

that is, 32K for windowBits=15 (default value) plus a few kilobytes for small objects.

This is in addition to a single internal output slab buffer of size chunkSize , which defaults to 16K.

The speed of zlib compression is affected most dramatically by the level setting. A higher level will result in
better compression, but will take longer to complete. A lower level will result in less compression, but will be
much faster.

In general, greater memory usage options will mean that node has to make fewer calls to zlib, since it'll be able to
process more data in a single write operation. So, this is another factor that affects the speed, at the cost of
memory usage.

Módulo os #
Utilice require('os') para acceder al módulo.

os.hostname()
http://nodejs-es.github.io/api/all.html 114/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

Devuelve el hostname del sistema operativo. #

os.type() #
Devuelve el nombre del sistema operativo.

os.release() #
Devuelve la versión del sistema operativo.

os.uptime() #
Devuelve el uptime en segundos del sistema.

os.loadavg() #
Devuelve un array conteniendo los promedios en 1, 5, y 15 minutos de carga.

os.totalmem() #
Devuelve la cantidad total en memoria del sistema en bytes

os.freemem() #
Devuelve la cantidad de memoria libre del sistema en bytes.

os.cpus() #
Devuelve un array de objetos que contiene información acerca de cada CPU/core instalado: modelo, velocidad
(en MHz), y los tiempos (un objeto que contiene el número de CPU usado por: usuario, nice, sys, idle, e irq).

Ejemplo de inspección de os.cpus:

[ { model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz',


speed: 2926,
times:
{ user: 252020,
nice: 0,
sys: 30340,
idle: 1070356870,
irq: 0 } },
{ model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz',
speed: 2926,
times:
{ user: 306960,
nice: 0,
sys: 26980,
idle: 1071569080,
irq: 0 } },
{ model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz',
speed: 2926,
times:
{ user: 248450,
nice: 0,
http://nodejs-es.github.io/api/all.html 115/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

sys: 21750,
idle: 1070919370,
irq: 0 } },
{ model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz',
speed: 2926,
times:
{ user: 256880,
nice: 0,
sys: 19430,
idle: 1070905480,
irq: 20 } },
{ model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz',
speed: 2926,
times:
{ user: 511580,
nice: 20,
sys: 40900,
idle: 1070842510,
irq: 0 } },
{ model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz',
speed: 2926,
times:
{ user: 291660,
nice: 0,
sys: 34360,
idle: 1070888000,
irq: 10 } },
{ model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz',
speed: 2926,
times:
{ user: 308260,
nice: 0,
sys: 55410,
idle: 1071129970,
irq: 880 } },
{ model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz',
speed: 2926,
times:
{ user: 266450,
nice: 1480,
sys: 34920,
idle: 1072572010,
irq: 30 } } ]

Depurador #

Stability: 3 - Stable

V8 viene con el complemento depurador (debugger), el cual puede ser accedido desde fuera del proceso vía el
protocolo TCP. Node posee un cliente incorporado para el depurador. Para usarlo, inicie Node con el argumento
debug ; y aparecerá:

% node debug myscript.js


< debugger listening on port 5858
connecting... ok

http://nodejs-es.github.io/api/all.html 116/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

break in /home/indutny/Code/git/indutny/myscript.js:1
1 x = 5;
2 setTimeout(function () {
3 debugger;
debug>

El cliente depurador de Node no soporta toda una gama de comandos, pero para cosas sencillas y tareas de
inspección es posible su uso. Al poner la declaración debugger; en el código fuente del script, permitirá un
punto de interrupción.

Por ejemplo, supongamos que myscript.js era así:

// myscript.js
x = 5;
setTimeout(function () {
debugger;
console.log("mundo");
}, 1000);
console.log("hola");

Entonces una vez que el depurador se ejecute, se generará un break en la línea 4.

% node debug myscript.js


< debugger listening on port 5858
connecting... ok
break in /home/indutny/Code/git/indutny/myscript.js:1
1 x = 5;
2 setTimeout(function () {
3 debugger;
debug> cont
< hello
break in /home/indutny/Code/git/indutny/myscript.js:3
1 x = 5;
2 setTimeout(function () {
3 debugger;
4 console.log("world");
5 }, 1000);
debug> next
break in /home/indutny/Code/git/indutny/myscript.js:4
2 setTimeout(function () {
3 debugger;
4 console.log("world");
5 }, 1000);
6 console.log("hello");
debug> repl
Press Ctrl + C to leave debug repl
> x
5
> 2+2
4
debug> next
< world
break in /home/indutny/Code/git/indutny/myscript.js:5
3 debugger;
4 console.log("world");
5 }, 1000);
6 console.log("hello");

http://nodejs-es.github.io/api/all.html 117/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

7
debug> quit
%

El comando repl te permite evaluar el código remotamente. El comando next continúa la siguiente línea. Hay
otros comandos disponibles y algunos más por venir de tipo ayuda. Escriba help para ver otros comandos.

Watchers #
You can watch expression and variable values while debugging your code. On every breakpoint each expression
from the watchers list will be evaluated in the current context and displayed just before the breakpoint's source
code listing.

To start watching an expression, type watch("my_expression") . watchers prints the active watchers. To
remove a watcher, type unwatch("my_expression") .

Commands reference #

Stepping #
cont, c - Continue execution
next, n - Step next
step, s - Step in
out, o - Step out
pause - Pause running code (like pause button in Developer TOols)

Breakpoints #
setBreakpoint(), sb() - Set breakpoint on current line
setBreakpoint(line), sb(line) - Set breakpoint on specific line
setBreakpoint('fn()'), sb(...) - Set breakpoint on a first statement in functions body
setBreakpoint('script.js', 1), sb(...) - Set breakpoint on first line of script.js
clearBreakpoint, cb(...) - Clear breakpoint

Info #
backtrace, bt - Print backtrace of current execution frame
list(5) - List scripts source code with 5 line context (5 lines before and after)
watch(expr) - Add expression to watch list
unwatch(expr) - Remove expression from watch list
watchers - List all watchers and their values (automatically listed on each breakpoint)
repl - Open debugger's repl for evaluation in debugging script's context

Execution control #
run - Run script (automatically runs on debugger's start)
restart - Restart script
kill - Kill script

http://nodejs-es.github.io/api/all.html 118/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

Various #
scripts - List all loaded scripts
version - Display v8's version

Uso avanzado #
El depurador V8 puede ser habilitado y accedido ya sea al iniciar Node con el comando --debug o al señalar un
proceso en Node existente con SIGUSR1 .

Cluster #

Stability: 1 - Experimental

A single instance of Node runs in a single thread. To take advantage of multi-core systems the user will
sometimes want to launch a cluster of Node processes to handle the load.

The cluster module allows you to easily create a network of processes that all share server ports.

var cluster = require('cluster');


var http = require('http');
var numCPUs = require('os').cpus().length;

if (cluster.isMaster) {
// Fork workers.
for (var i = 0; i < numCPUs; i++) {
cluster.fork();
}

cluster.on('death', function(worker) {
console.log('worker ' + worker.pid + ' died');
});
} else {
// Workers can share any TCP connection
// In this case its a HTTP server
http.createServer(function(req, res) {
res.writeHead(200);
res.end("hello world\n");
}).listen(8000);
}

Running node will now share port 8000 between the workers:

% node server.js
Worker 2438 online
Worker 2437 online

This feature was introduced recently, and may change in future versions. Please try it out and provide feedback.

cluster.settings #
Object
exec String file path to worker file. (Default=__filename)

http://nodejs-es.github.io/api/all.html 119/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

args Array string arguments passed to worker. (Default=process.argv.slice(2))


silent Boolean whether or not to send output to parent's stdio. (Default=false)

All settings set by the .setupMaster is stored in this settings object. This object is not supposed to be change or
set manually, by you.

cluster.isMaster #
Boolean

True if the process is a master. This is determined by the process.env.NODE_UNIQUE_ID . If


process.env.NODE_UNIQUE_ID is undefined, then isMaster is true .

cluster.isWorker #
Boolean

This boolean flag is true if the process is a worker forked from a master. If the process.env.NODE_UNIQUE_ID
is set to a value, then isWorker is true .

Event: 'fork' #
worker Worker object

When a new worker is forked the cluster module will emit a 'fork' event. This can be used to log worker activity,
and create you own timeout.

var timeouts = [];


var errorMsg = function () {
console.error("Something must be wrong with the connection ...");
});

cluster.on('fork', function (worker) {


timeouts[worker.uniqueID] = setTimeout(errorMsg, 2000);
});
cluster.on('listening', function (worker) {
clearTimeout(timeouts[worker.uniqueID]);
});
cluster.on('death', function (worker) {
clearTimeout(timeouts[worker.uniqueID]);
errorMsg();
});

Event: 'online' #
worker Worker object

After forking a new worker, the worker should respond with a online message. When the master receives a online
message it will emit such event. The difference between 'fork' and 'online' is that fork is emitted when the master
tries to fork a worker, and 'online' is emitted when the worker is being executed.

cluster.on('online', function (worker) {


console.log("Yay, the worker responded after it was forked");
});

http://nodejs-es.github.io/api/all.html 120/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

Event: 'listening' #
worker Worker object

When calling listen() from a worker, a 'listening' event is automatically assigned to the server instance. When
the server is listening a message is send to the master where the 'listening' event is emitted.

cluster.on('listening', function (worker) {


console.log("We are now connected");
});

Event: 'death' #
worker Worker object

When any of the workers die the cluster module will emit the 'death' event. This can be used to restart the worker
by calling fork() again.

cluster.on('death', function(worker) {
console.log('worker ' + worker.pid + ' died. restart...');
cluster.fork();
});

Event: 'setup' #
worker Worker object

When the .setupMaster() function has been executed this event emits. If .setupMaster() was not executed
before fork() this function will call .setupMaster() with no arguments.

cluster.setupMaster([settings]) #
settings Object
exec String file path to worker file. (Default=__filename)
args Array string arguments passed to worker. (Default=process.argv.slice(2))
silent Boolean whether or not to send output to parent's stdio. (Default=false)

The setupMaster is used to change the default 'fork' behavior. It takes one option object argument.

Example:

var cluster = require("cluster");


cluster.setupMaster({
exec : "worker.js",
args : ["--use", "https"],
silent : true
});
cluster.autoFork();

cluster.fork([env]) #
env Object Key/value pairs to add to child process environment.
return Worker object
http://nodejs-es.github.io/api/all.html 121/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

Spawn a new worker process. This can only be called from the master process.

cluster.settings #
Object
exec String file path to worker file. Default: __filename
args Array string arguments passed to worker. (Default=process.argv.slice(2))
silent Boolean whether or not to send output to parent's stdio. (Default=false)

All settings set by the .setupMaster is stored in this settings object. This object is not supposed to be change or
set manually.

cluster.workers #
Object

In the cluster all living worker objects are stored in this object by there uniqueID as the key. This makes it easy
to loop through all living workers.

// Go through all workers


function eachWorker(callback) {
for (var uniqueID in cluster.workers) {
callback(cluster.workers[uniqueID]);
}
}
eachWorker(function (worker) {
worker.send('big announcement to all workers');
});

Should you wish to reference a worker over a communication channel, using the worker's uniqueID is the easiest
way to find the worker.

socket.on('data', function (uniqueID) {


var worker = cluster.workers[uniqueID];
});

Class: Worker #
A Worker object contains all public information and method about a worker. In the master it can be obtained
using cluster.workers . In a worker it can be obtained using cluster.worker .

worker.uniqueID #
String

Each new worker is given its own unique id, this id is stored in the uniqueID .

While a worker is alive, this is the key that indexes it in cluster.workers

worker.process #
ChildProcess object

http://nodejs-es.github.io/api/all.html 122/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

All workers are created using child_process.fork() , the returned object from this function is stored in
process.

See: Child Process module

worker.suicide #
Boolean

This property is a boolean. It is set when a worker dies, until then it is undefined . It is true if the worker was
killed using the .destroy() method, and false otherwise.

worker.send(message, [sendHandle]) #
message Object
sendHandle Handle object

This function is equal to the send methods provided by child_process.fork() . In the master you should use
this function to send a message to a specific worker. However in a worker you can also use
process.send(message) , since this is the same function.

This example will echo back all messages from the master:

if (cluster.isMaster) {
var worker = cluster.fork();
worker.send('hi there');

} else if (cluster.isWorker) {
process.on('message', function (msg) {
process.send(msg);
});
}

worker.destroy() #
This function will kill the worker, and inform the master to not spawn a new worker. To know the difference
between suicide and accidentally death a suicide boolean is set to true.

cluster.on('death', function (worker) {


if (worker.suicide === true) {
console.log('Oh, it was just suicide\' – no need to worry').
}
});

// destroy worker
worker.destroy();

Event: 'message' #
message Object

This event is the same as the one provided by child_process.fork() . In the master you should use this event,
http://nodejs-es.github.io/api/all.html 123/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

however in a worker you can also use process.on('message')

As an example, here is a cluster that keeps count of the number of requests in the master process using the
message system:

var cluster = require('cluster');


var http = require('http');

if (cluster.isMaster) {

// Keep track of http requests


var numReqs = 0;
setInterval(function() {
console.log("numReqs =", numReqs);
}, 1000);

// Count requestes
var messageHandler = function (msg) {
if (msg.cmd && msg.cmd == 'notifyRequest') {
numReqs += 1;
}
};

// Start workers and listen for messages containing notifyRequest


cluster.autoFork();
Object.keys(cluster.workers).forEach(function (uniqueID) {
cluster.workers[uniqueID].on('message', messageHandler);
});

} else {

// Worker processes have a http server.


http.Server(function(req, res) {
res.writeHead(200);
res.end("hello world\n");

// notify master about the request


process.send({ cmd: 'notifyRequest' });
}).listen(8000);
}

Event: 'online' #
worker Worker object

Same as the cluster.on('online') event, but emits only when the state change on the specified worker.

cluster.fork().on('online', function (worker) {


// Worker is online
};

Event: 'listening' #
worker Worker object

http://nodejs-es.github.io/api/all.html 124/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

Same as the cluster.on('listening') event, but emits only when the state change on the specified worker.

cluster.fork().on('listening', function (worker) {


// Worker is listening
};

Event: 'death' #
worker Worker object

Same as the cluster.on('death') event, but emits only when the state change on the specified worker.

cluster.fork().on('death', function (worker) {


// Worker has died
};

Apéndice 1 - Módulos de terceros #


Existen muchos módulos de terceros para Node. En el momento de escribir esto, Agosto 2010, el repositorio
principal de módulos es esta página del wiki.

Este apéndice pretente ser una pequeña guía de ayuda a los recién llegados a que puedan encontrar rápidamente
módulos de calidad. No prentede ser una lista completa. Ya que se puede encontrar mejores módulos y más
completos en donde sea.

Module Installer: npm


HTTP Middleware: Connect
Web Framework: Express
Web Sockets: Socket.IO
HTML Parsing: HTML5
mDNS/Zeroconf/Bonjour
RabbitMQ, AMQP
mysql
Serialization: msgpack
Scraping: Apricot
Debugger: ndb is a CLI debugger inspector is a web based tool.
pcap binding
ncurses
Testing/TDD/BDD: vows, mocha, mjsunit.runner

Parches a esta lista son bienvenidos.

Node.js Node.js en español @nodejs_es

Copyright Joyent, Inc, Node.js is a trademark of Joyent, Inc. View license.

http://nodejs-es.github.io/api/all.html 125/126
15/8/2015 Acerca de esta documentación Node.js v0.6.19 Manual & Documentación

http://nodejs-es.github.io/api/all.html 126/126

Potrebbero piacerti anche