GithubHelp home page GithubHelp logo

cronet.js's Introduction

Cronet.js

Cronet's native API bindings for Node.js.

Installation

This native addon uses CMake.js to build when package install.

So we will need to fulfill its requirements at first.

npm install cronet

Usage

const { Buffer } = require('node:buffer')
const cronetjs = require('cronet')
const {
  CronetEngineParams,
  CronetEngine,
  CronetExecutor,
  CronetUrlRequestCallback,
  CronetUrlRequestParams,
  CronetUrlRequest,
} = cronetjs

// dynamic load library
CronetEngine.loadLibrary('libcronet.so')

const params = new CronetEngineParams()
params.enableQuic = true // by default
const engine = new CronetEngine()
console.log('CronetEngine version: ' + engine.versionString)
engine.startWithParams(params)

const executor = new CronetExecutor()
executor.start()

function newRequest(url, timeout = 2000) {
  return new Promise((resolve, reject) => {
    const urlReq = new CronetUrlRequest()

    let body = null

    let t = setTimeout(function () {
      if (!t) {
        return
      }
      console.log('Request timeout.')
      t = null
      urlReq.cancel()
    }, timeout)

    const done = function () {
      if (t) {
        clearTimeout(t)
        t = null
      }
      resolve(body)
    }

    const urlReqParams = new CronetUrlRequestParams()
    urlReqParams.httpMethod = 'GET'
    urlReqParams.disableCache = true

    const urlCallback = new CronetUrlRequestCallback()
    urlCallback.onRedirectReceived = function (request, info, newLocationUrl) {
      console.log('onFollowRedirect: ' + info.httpStatusCode + ' ' + newLocationUrl)
      request.followRedirect()
    }
    urlCallback.onResponseStarted = function (request, info) {
      console.log('onResponseStarted: ' + info.url
        + ' ' + info.negotiatedProtocol
        + ' ' + info.httpStatusCode + ' ' + info.httpStatusText)

      console.log('All headers:')
      const allHeadersListSize = info.allHeadersListSize()
      for (let i = 0; i < allHeadersListSize; i++) {
        const header = info.allHeadersListAt(i)
        console.log({ name: header.name, value: header.value })
      }

      let buffer = new cronetjs.CronetBuffer()
      // Create and allocate 32kb buffer.
      buffer.initWithAlloc(32 * 1024)
      // Started reading the response.
      request.read(buffer)
    }
    urlCallback.onReadCompleted = function (request, info, buffer, bytesRead) {
      console.log('onReadCompleted, bytes read: ' + bytesRead)
      const bytes = buffer.data.slice(0, bytesRead)
      if (!body) {
        body = Buffer.from(bytes)
      } else {
        body = Buffer.concat([body, bytes])
      }
      // Continue reading the response.
      request.read(buffer)
    }
    urlCallback.onSucceeded = function (request, info) {
      console.log('onSucceeded')
      done()
    }
    urlCallback.onFailed = function (request, info, error) {
      console.log('onFailed, message: ' + error.message
        + ', error_code: ' + error.errorCode
        + ', internal_error_code: ' + error.internalErrorCode)
      done()
    }
    urlCallback.onCanceled = function (request, info) {
      console.log('onCanceled')
      done()
    }

    urlReq.initWithParams(engine, url, urlReqParams, urlCallback, executor)
    urlReq.start()
  })
}

async function main() {
  await newRequest('https://google.com/', 2000)
  executor.shutdown()
  engine.shutdown()
}

main()

cronet.js's People

Contributors

tengattack avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.