Saltar al contenido principal

net

Emitir solicitudes HTTP/HTTPS usando la biblioteca de red nativa de Chromium

Proceso: principal</0>

El módulo net es un lado del cliente API para tratar pedidos HTTP(S). Si es similar a los módulos HTTP y HTTPS de Node.js pero usa la biblioteca de la red nativa de Chromium en vez de las aplicaciones Node.js, ofreciendo un mejor soporte a los proxies de la web. It also supports checking network status.

La siguiente es una lista no completa de por qué debería considerar usar el módulo net en vez de los módulos nativos Node.js:

  • Gestión automática del sistema de configuración de proxy, soporte del protocolo wpad y el paquete de archivos de configuración del proxy.
  • Túnel automático para peticiones HTTPS.
  • Soportar los proxies de autentificación usando basic, digest, NTLM, Kerberos, o negociar esquemas de autentificación.
  • Soporta proxies para monitoreo de tráfico: Fiddler como proxies usados para el acceso, el control y el monitoreo.

Los componentes API (incluyendo clases, métodos, propiedades y nombres de eventos) son similares a esos usados en Node.js.

Ejemplo de uso:

const { app } = require('electron')
app.whenReady().then(() => {
const { net } = require('electron')
const request = net.request('https://github.com')
request.on('response', (response) => {
console.log(`STATUS: ${response.statusCode}`)
console.log(`HEADERS: ${JSON.stringify(response.headers)}`)
response.on('data', (chunk) => {
console.log(`BODY: ${chunk}`)
})
response.on('end', () => {
console.log('No more data in response.')
})
})
request.end()
})

La API net puede ser utilizada solo después que la aplicación emita el evento ready. Intentar usar el módulo antes del evento ready lanzará un error.

Métodos

El módulo net tiene los siguientes métodos:

net.request(options)

Devuelve ClientRequest

Crea una instancia ClientRequest usando la options proveída la cual son directamente reenviadas al constructor ClientRequest. El método net.request será usado para emitir solicitudes HTTP tanto seguras como inseguras dependiendo de lo especificado en el esquema de protocolo en el objeto options.

net.isOnline()

Devuelve boolean - Si actualmente hay conexión a internet.

A return value of false is a pretty strong indicator that the user won't be able to connect to remote sites. However, a return value of true is inconclusive; even if some link is up, it is uncertain whether a particular connection attempt to a particular remote site will be successful.

net.resolveHost(host, [options])

  • host string - Hostname to resolve.
  • options Object (opcional)
    • queryType string (optional) - Requested DNS query type. If unspecified, resolver will pick A or AAAA (or both) based on IPv4/IPv6 settings:
      • A - Fetch only A records
      • AAAA - Fetch only AAAA records.
    • source string (optional) - The source to use for resolved addresses. Default allows the resolver to pick an appropriate source. Only affects use of big external sources (e.g. calling the system for resolution or using DNS). Even if a source is specified, results can still come from cache, resolving "localhost" or IP literals, etc. Uno de los siguiente valores:
      • any (default) - Resolver will pick an appropriate source. Results could come from DNS, MulticastDNS, HOSTS file, etc
      • system - Results will only be retrieved from the system or OS, e.g. via the getaddrinfo() system call
      • dns - Results will only come from DNS queries
      • mdns - Results will only come from Multicast DNS queries
      • localOnly - No external sources will be used. Results will only come from fast local sources that are available no matter the source setting, e.g. cache, hosts file, IP literal resolution, etc.
    • cacheUsage string (optional) - Indicates what DNS cache entries, if any, can be used to provide a response. Uno de los siguiente valores:
      • allowed (default) - Results may come from the host cache if non-stale
      • staleAllowed - Results may come from the host cache even if stale (by expiration or network changes)
      • disallowed - Results will not come from the host cache.
    • secureDnsPolicy string (optional) - Controls the resolver's Secure DNS behavior for this request. Uno de los siguiente valores:
      • allow (default)
      • disable

Returns Promise<ResolvedHost> - Resolves with the resolved IP addresses for the host.

This method will resolve hosts from the default session. To resolve a host from another session, use ses.resolveHost().

Propiedades

net.online SoloLectura

Una propiedad boolean. Whether there is currently internet connection.

A return value of false is a pretty strong indicator that the user won't be able to connect to remote sites. However, a return value of true is inconclusive; even if some link is up, it is uncertain whether a particular connection attempt to a particular remote site will be successful.