Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
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
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.
Stability: 1 Experimental
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.
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':
Para ejecutar el servidor, copie el código en un fichero llamado example.js y ejecútelo con el programa node
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}
console #
{Object}
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.
console.log(__filename);
// /Users/mjr/example.js
__dirname #
{String}
console.log(__dirname);
// /Users/mjr
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.
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.
setTimeout(cb, ms) #
clearTimeout(t) #
setInterval(cb, ms) #
clearInterval(t) #
The timer functions are global variables. See the timers section.
console #
{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:
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 #
clearTimeout(timeoutId) #
Evita la ejecución de un callback por uno de sus disparadores.
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 :
El contenido de circle.js :
var PI = Math.PI;
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
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.
/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.
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.
/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
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" }
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
[ '/home/micheil/.node_modules',
'/usr/local/lib/node_modules' ]
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.
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.
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.
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
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.
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:
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.
exports.hello = 'world';
#include <v8.h>
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'
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:
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.
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).
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);
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.
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 .
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.
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('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á:
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.
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.
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 .
process.exit(1);
process.getgid() #
Obtiene la identidad de grupo del proceso. (Mirar getgid(2).) Es el id de grupo numérico, no el nombre del grupo.
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.
process.getuid() #
Obtiene la identidad de usuario del proceso. (Mirar getuid(2).) Es la id de usuario númerica, no el nombre de
usuario.
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.
process.version #
Una propiedad dentro del compilado que expone NODE_VERSION .
process.installPrefix #
Una propiedad dentro del compilado que expone NODE_PREFIX .
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.
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.
process.title #
Getter/setter para establecer lo que mostrará 'ps'.
process.platform #
En que plataforma se está ejecutando. 'linux2' , 'darwin' , etc.
process.memoryUsage() #
Devuelve un objeto describiendo el uso de la memoria del proceso Node.
console.log(util.inspect(process.memoryUsage()));
Generará:
{ rss: 4935680,
vsize: 41893888,
heapTotal: 1826816,
heapUsed: 650472 }
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.
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.
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.
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.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 .
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
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 .
util.isArray(object) #
Returns true if the given "object" is an Array . false otherwise.
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.
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
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.
util.isError(new Error())
// true
util.isError(new TypeError())
// true
util.isError({ name: 'Error', message: 'an error occurred' })
// false
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 .
function MyStream() {
events.EventEmitter.call(this);
}
util.inherits(MyStream, events.EventEmitter);
MyStream.prototype.write = function(data) {
this.emit("data", data);
}
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
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.
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
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.
Event: 'newListener' #
function (event, 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.
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
new Buffer(array) #
array Array
Allocates a new buffer containing the given str . encoding defaults to '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.
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
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.
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 ).
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 .
str = "node.js";
buf = new Buffer(str.length);
console.log(buf);
// node.js
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
// ½ + ¼ = ¾: 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.
console.log(buf.length);
buf.write("some string", "ascii", 0);
console.log(buf.length);
// 1234
// 1234
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 .
// !!!!!!!!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
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.
// 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:
buf[0] = 0x3;
buf[1] = 0x4;
buf[2] = 0x23;
buf[3] = 0x42;
// 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:
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:
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:
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:
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
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:
console.log(buf);
// <Buffer 03 04 23 42>
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:
console.log(buf);
buf.writeUInt16LE(0xdead, 0);
buf.writeUInt16LE(0xbeef, 2);
console.log(buf);
// <Buffer de ad be ef>
// <Buffer ad de ef be>
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:
console.log(buf);
buf.writeUInt32LE(0xfeedface, 0);
console.log(buf);
// <Buffer fe ed fa ce>
// <Buffer ce fa ed fe>
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 .
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 .
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 .
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:
console.log(buf);
buf.writeFloatLE(0xcafebabe, 0);
console.log(buf);
// <Buffer 4f 4a fe bb>
// <Buffer bb fe 4a 4f>
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:
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>
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.
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) { }
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.
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.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
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) { }
Event: 'close' #
function () { }
Event: 'pipe' #
function (src) { }
stream.writable #
A boolean that is true by default, but turns false after an 'error' occurred or end() / destroy() was
called.
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
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:
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.
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).
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.
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.
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.
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.
alice.generateKeys();
bob.generateKeys();
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:
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:
Para crear un certificado auto firmado con el CSR, hay que hacer:
(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)
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.
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.
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.
var options = {
key: fs.readFileSync('server-key.pem'),
cert: fs.readFileSync('server-cert.pem')
};
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.
Esta función es asíncrona. El último parámetro callback se invocará cuando el servidor esté saturado.
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 .
var fs = require('fs');
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
It could be that fs.stat is executed before fs.rename . The correct way to do this is to chain the callbacks.
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.renameSync(path1, path2) #
Synchronous rename(2).
fs.truncateSync(fd, len) #
Synchronous ftruncate(2).
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' }
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.linkSync(srcpath, dstpath) #
Synchronous link(2).
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.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).
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.
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.
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
The callback is passed two arguments (err, data) , where data is the contents of the file.
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.
Example:
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
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 ).
{ 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.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
Event: 'open' #
function (fd) { }
fs.createWriteStream(path, [options]) #
Returns a new WriteStream object (See Writable Stream ).
{ 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.
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'
Example:
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
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.
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.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
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.
{ 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:
To listen on the socket /tmp/echo.sock the third line from the last would just be changed to
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 UNIX domain sockets, options argument should be an object which specifies:
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.
To connect on the socket /tmp/echo.sock the second line would just be changed to
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.
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.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:
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
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.
Event: 'listening' #
Emitted when the server has been bound after calling server.listen .
Event: 'connection' #
Socket object The connection object
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
{ 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.
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 .
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.
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.
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.
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
Event: 'drain' #
Emitted when the write buffer becomes empty. Can be used to throttle uploads.
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.
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 .
Ejemplo de envío de un mensaje al syslogd en OSX via un socket de dominio Unix /var/run/syslog :
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
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:
server.on("listening", function () {
console.log("servidor escuchando " + server.address().address);
})
server.bind(serverPath);
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.
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
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 .
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.
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.
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
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 ).
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
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.
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': '/' }
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) { }
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) { }
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.
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) {}
http.createServer(requestListener) #
Devuelve un nuevo objeto de servidor web.
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.
Event: 'data' #
function (chunk) { }
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
request.url #
Request URL string. This contains only the URL that is present in the actual HTTP request. If the request is:
'/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:
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
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.
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 .
Example:
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.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:
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.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.
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.
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
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.
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 inprogress 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
});
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 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' .
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.
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) {}
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
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.request(options, callback) #
Hace una petición a un servidor web seguro. Opciones similares a http.request() .
Ejemplo:
var options = {
host: 'encrypted.google.com',
port: 443,
path: '/',
method: 'GET'
};
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
});
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.
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);
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
};
https.get(options, callback) #
Con http.get() pero para HTTPS.
Ejemplo:
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
host : Una parte del host de la URL completa, incluyendo la información del puerto y autentificación.
Ejemplo: 'user:pass@host.com: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'
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
Ejemplo:
querystring.stringify({foo: 'bar'})
// devuelve
'foo=bar'
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
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:
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
});
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.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 .
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:
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:
connections = 0;
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.
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;
.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 ./file/to/load.js
<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
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.
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.
Example: compile and execute code that increments a global variable and sets a new one. These globals are
contained in the sandbox.
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
};
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.
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;
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.
console.log(util.inspect(sandbox));
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
Es posible pasar un stream de datos a través del stdin , stdout , y stderr del proceso hijo (child) de manera
totalmente sin bloqueo.
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
If the child stdio streams are shared with the parent, then this will not be set.
child.stderr #
Stream object
If the child stdio streams are shared with the parent, then this will not be set.
child.pid #
Integer
Ejemplo:
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.
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
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
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.
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.
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.
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.
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');
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
And then the child script, 'sub.js' might look like this:
process.on('message', function(m) {
console.log('CHILD got message:', m);
});
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:
Here is an example of receiving the server handle and sharing it between processes:
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.ok(value, [message]) #
Evalua si el valor es true , si es equivalente a assert.equal(true, value, message);
assert.throws(
function() {
throw new Error("Wrong value");
},
Error
);
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/
);
assert.throws(
function() {
throw new Error("Wrong value");
},
function(err) {
if ( (err instanceof Error) && /value/.test(err) ) {
return true;
}
},
"unexpected error"
);
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:
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.
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
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.getWindowSize(fd) #
Devuelve [row, col] associado a la TTY con el descriptor de fichero.
Zlib #
Stability: 3 - Stable
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.
inp.pipe(gzip).pipe(out);
Compressing or decompressing data in one step can be done by using the convenience methods.
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.
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 = '';
}
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
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
Note that some options are only relevant when compressing, and are ignored by the decompression classes.
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:
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
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).
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á:
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.
// myscript.js
x = 5;
setTimeout(function () {
debugger;
console.log("mundo");
}, 1000);
console.log("hola");
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.
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
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
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.
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.
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.
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:
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.
Should you wish to reference a worker over a communication channel, using the worker's uniqueID is the easiest
way to find the worker.
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 .
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.
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.
// 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
As an example, here is a cluster that keeps count of the number of requests in the master process using the
message system:
if (cluster.isMaster) {
// Count requestes
var messageHandler = function (msg) {
if (msg.cmd && msg.cmd == 'notifyRequest') {
numReqs += 1;
}
};
} else {
Event: 'online' #
worker Worker object
Same as the cluster.on('online') event, but emits only when the state change on the specified worker.
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.
Event: 'death' #
worker Worker object
Same as the cluster.on('death') event, but emits only when the state change on the specified worker.
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.
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