Перейти к основному содержанию

net

Выполнение HTTP/HTTPS запросов с использованием родной сетевой библиотеки Chromium

Процесс: Главный

Модуль net представляет собой клиентский API для выдачи HTTP(S) запросов. Он похож на модули HTTP и HTTPS в Node.js, но использует собственную сетевую библиотеку Chromium вместо реализации Node.js, обеспечивая лучшую поддержку веб-прокси. It also supports checking network status.

Ниже приведен неполный список причин, по которым вы можете рассмотреть использование модуля net вместо собственных модулей Node.js:

  • Автоматическое управление конфигурацией прокси системы, поддержка протокола wpad и файлов pac конфигурации прокси.
  • Автоматическое туннелирование HTTPS запросов.
  • Поддержка аутентификации прокси с помощью BASIC, DIGEST, NTLM, KERBEROS или NEGOTIATE схем аутентификации.
  • Поддержка прокси-серверов для мониторинга трафика: Fiddler-подобные прокси, используемые для контроля доступа и мониторинга.

Компоненты API (включая классы, методы, свойства и имена событий) похожи на компоненты, используемые в Node.js.

Пример использования:

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()
})

The net API can be used only after the application emits the ready event. Trying to use the module before the ready event will throw an error.

Методы

Модуль net имеет следующие методы:

net.request(options)

Возвращает ClientRequest

Creates a ClientRequest instance using the provided options which are directly forwarded to the ClientRequest constructor. Метод net.request будет использован для выполнения как безопасных, так и небезопасных HTTP-запросов в соответствии со схемой указанного протокола в объекте options.

net.isOnline()

Returns 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.

net.resolveHost(host, [options])

  • host string - Hostname to resolve.
  • options Object (опционально)
    • 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. Одно из следующих значений:
      • 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. Одно из следующих значений:
      • 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. Одно из следующих значений:
      • allow (default)
      • отключить

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().

Свойства

net.online Только чтение

A boolean property. 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.