@u4/adbkit
    Preparing search index...

    Class DeviceClient

    Index
    client: Client
    serial: string
    • Reattaches ADB to the device's ADB USB interface. This re-enables communication between ADB and device, reversing detach().

      Returns Promise<boolean>

      true

    • Checks whether a given system service is registered.

      Parameters

      • serviceName: string

      Returns Promise<boolean>

      true if the service is available.

    • Deletes all data associated with a package from the device. This is roughly analogous to adb shell pm clear <pkg>.

      Parameters

      • pkg: string

        The package name. This is NOT the APK.

      Returns Promise<boolean>

      true

    • Detaches ADB's USB interface from ADB. This releases the device from ADB control, allowing other processes to use it.

      Returns Promise<boolean>

      true

    • Execute a single command and get stdout response as a Buffer or string.

      Parameters

      • command: string | ArrayLike<WithToString>

        the command to execute

      Returns Promise<Buffer<ArrayBufferLike>>

    • Execute a single command and get stdout response as a Buffer or string.

      Parameters

      • command: string | ArrayLike<WithToString>

        the command to execute

      • encoding: BufferEncoding

      Returns Promise<string>

    • Forwards socket connections from the ADB server host (local) to the device (remote). This is analogous to adb forward <local> <remote>. It's important to note that if you are connected to a remote ADB server, the forward will be created on that host.

      Parameters

      • local: string

        A string representing the local endpoint on the ADB host. At time of writing, can be one of:

        • tcp:<port>
        • localabstract:<unix domain socket name>
        • localreserved:<unix domain socket name>
        • localfilesystem:<unix domain socket name>
        • dev:<character device name>
      • remote: string

        A string representing the remote endpoint on the device. At time of writing, can be one of: Any value accepted by the local argument jdwp:<process pid>

      Returns Promise<boolean>

      true

    • Fetches the current raw framebuffer (i.e. what is visible on the screen) from the device, and optionally converts it into something more usable by using GraphicsMagick's gm command, which must be available in $PATH if conversion is desired.

      Parameters

      • format: string = 'raw'

        The desired output format. Defaults to 'raw' for raw framebuffer data.

      Returns Promise<FramebufferStreamWithMeta>

      The possibly converted framebuffer stream. The stream also has a meta property.

    • Gets the device path of the device identified by the given serial number.

      Returns Promise<string>

      The device path. This corresponds to the device path in client.listDevicesWithPaths().

      List devices with paths

      import Adb from '@u4/adbkit';
      const client = Adb.createClient();
      const devices = await client.listDevicesWithPaths();
      for (const d of devices) {
      console.log('id:', d.id);
      console.log('type:', d.type);
      console.log('model:', d.model);
      console.log('path:', d.path);
      console.log('product:', d.product);
      console.log('transportId:', d.transportId);
      }
    • Retrieves the features of the device identified by the given serial number. This is analogous to adb shell pm list features. Useful for checking whether hardware features such as NFC are available (you'd check for 'android.hardware.nfc').

      Returns Promise<Features>

      An object of device features. Each key corresponds to a device feature, with the value being either true for a boolean feature, or the feature value as a string (e.g. '0x20000' for reqGlEsVersion).

      Checking for NFC support

      import Adb from '@u4/adbkit';

      const client = Adb.createClient();

      const test = async () => {
      try {
      const devices = await client.listDevices();
      const supportedDevices: string[] = [];
      for (const device of devices) {
      const deviceClient = device.getClient();
      const features = await deviceClient.getFeatures();
      if (features['android.hardware.nfc'])
      supportedDevices.push(device.id);
      }
      console.log('The following devices support NFC:', supportedDevices);
      } catch (err) {
      console.error('Something went wrong:', err);
      }
      };
    • Attempts to retrieve the IP addresses of the device using ip addr show.

      Parameters

      • Optionaliface: string = 'wlan0'

        The network interface. Defaults to 'wlan0'.

      Returns Promise<string[]>

      The IP addresses as string[] starting with IPv4 then IPv6.

    • Retrieves the list of packages present on the device. This is analogous to adb shell pm list packages. If you just want to see if something's installed, consider using device.isInstalled() instead.

      Parameters

      • ...flags: string[]

        Flags to pass to the pm list packages command to filter the list -d: filter to only show disabled packages -e: filter to only show enabled packages -s: filter to only show system packages -3: filter to only show third party packages

      Returns Promise<string[]>

      An array of package names installed on the device.

    • Retrieves the properties of the device identified by the given serial number. This is analogous to adb shell getprop.

      Returns Promise<Properties>

      An object of device properties. Each key corresponds to a device property. Convenient for accessing things like 'ro.product.model'.

    • Retrieves the list of running processes.

      Parameters

      • ...flags: string[]

        Optional flags passed to ps.

      Returns Promise<Partial<PsEntry>[]>

      A PsEntry array.

    • Gets the serial number of the device identified by the given serial number. With our API this doesn't really make much sense, but it has been implemented for completeness. FYI: in the raw ADB protocol you can specify a device in other ways, too.

      Returns Promise<string>

      The serial number of the device.

    • Gets the state of the device identified by the given serial number.

      Returns Promise<
          | "emulator"
          | "device"
          | "offline"
          | "unauthorized"
          | "recovery"
          | "unknown",
      >

      The device state. This corresponds to the device type in client.listDevices().

    • Installs the APK on the device, replacing any previously installed version. This is roughly analogous to adb install -r <apk>.

      Note that if the call seems to stall, you may have to accept a dialog on the phone first.

      Parameters

      • apk: string | Readable

        When String, interpreted as a path to an APK file. When Readable, installs directly from the stream, which must be a valid APK.

      Returns Promise<boolean>

      true

      Install an APK streamed from a URL using native fetch

      import Adb from '@u4/adbkit';
      import { Readable } from 'node:stream';

      const client = Adb.createClient();

      const test = async () => {
      try {
      const device = client.getDevice('<serial>');
      const res = await fetch('http://example.org/app.apk');
      if (!res.ok || !res.body) throw new Error(`HTTP ${res.status}`);
      await device.install(Readable.fromWeb(res.body));
      console.log('Installed');
      } catch (err) {
      console.error('Something went wrong:', err);
      }
      };

      Install an apk to all connected devices

      import Adb from '@u4/adbkit';

      const client = Adb.createClient();
      const apk = 'vendor/app.apk';

      const test = async () => {
      try {
      const devices = await client.listDevices();
      for (const device of devices) {
      await device.getClient().install(apk);
      console.log(`Installed ${apk} on ${device.id}`);
      }
      } catch (err) {
      console.error('Something went wrong:', err);
      }
      };
    • Installs an APK file which must already be located on the device file system, and replaces any previously installed version. Useful if you've previously pushed the file to the device (perhaps to have direct access to device.push()'s transfer stats). This is roughly analogous to adb shell pm install -r <apk> followed by adb shell rm -f <apk>.

      Note that if the call seems to stall, you may have to accept a dialog on the phone first.

      Parameters

      • apk: string

        The path to the APK file on the device. The file will be removed when the command completes.

      Returns Promise<boolean>

      true

    • Call ip route command. Pass each argument separately, e.g. ipRoute('list', 'table', 'all').

      Parameters

      • ...args: string[]

      Returns Promise<IpRouteEntry[]>

      An IpRouteEntry array.

    • Tells you if the specific package is installed or not. This is analogous to adb shell pm path <pkg> and some output parsing.

      Parameters

      • pkg: string

        The package name. This is NOT the APK.

      Returns Promise<boolean>

      true if the package is installed, false otherwise.

    • Lists forwarded connections on the device. This is analogous to adb forward --list.

      Returns Promise<Forward[]>

      An array of forward objects with serial, local, and remote.

    • List packages installed on the device.

      Parameters

      • Optionaloptions: { thirdparty?: boolean }

        list all or only third-party apps

      Returns Promise<DevicePackage[]>

      an array of DevicePackage

    • Lists reversed connections on the device. This is analogous to adb reverse --list.

      Returns Promise<Reverse[]>

      An array of Reverse objects with remote and local.

    • Opens a direct connection to a unix domain socket in the given path.

      Parameters

      • path: string

        The path to the socket. Prefixed with 'localfilesystem:' by default, include another prefix (e.g. 'localabstract:') in the path to override.

      Returns Promise<Duplex>

      The connection (Duplex). Call conn.end() to end the connection.

    • Parameters

      • path: string
      • _debugCtxt: string = ''

      Returns Promise<PromiseDuplex<Duplex>>

      Use openLocal wrapped in PromiseDuplex instead.

    • Opens a direct connection to a binary log file, providing access to the raw log data. Note that it is usually much more convenient to use openLogcat().

      Parameters

      • name: string

        The name of the log. Available logs include 'main', 'system', 'radio' and 'events'.

      Returns Promise<Duplex>

      The binary log stream. Call log.end() when you wish to stop receiving data.

    • Calls the logcat utility on the device and hands off the connection to @u4/adbkit-logcat.

      Parameters

      • options: { clear?: boolean } = {}

        Optional. Set clear: true to clear logcat before opening the reader.

      Returns Promise<Logcat>

      The Logcat client.

    • Starts the built-in monkey utility on the device, connects to it using openTcp() and hands the connection to @u4/adbkit-monkey.

      Parameters

      • port: number = 1080

        Optional. The device port where you'd like Monkey to run at. Defaults to 1080.

      Returns Promise<Client>

      The Monkey client.

    • Tracks /proc/stat and emits CPU load calculations once per second.

      Returns Promise<ProcStat>

      The /proc/stat tracker (EventEmitter). Call stat.end() to stop tracking.

    • Opens a direct TCP connection to a port on the device, without any port forwarding required.

      Parameters

      • port: number

        The port number to connect to.

      • Optionalhost: string

        Optional. The host to connect to.

      Returns Promise<Duplex>

      The TCP connection (Duplex). Call conn.end() to end the connection.

    • A convenience shortcut for sync.pull(), mainly for one-off use cases. The Sync client is closed automatically.

      Parameters

      • path: string

        See sync.pull() for details.

      Returns Promise<PullTransfer>

      A PullTransfer instance.

      Pulling a file from all connected devices

      import fs from 'node:fs';
      import Adb from '@u4/adbkit';
      const client = Adb.createClient();

      const test = async () => {
      try {
      const devices = await client.listDevices();
      await Promise.all(devices.map(async (device) => {
      const transfer = await device.getClient().pull('/system/build.prop');
      const fn = `/tmp/${device.id}.build.prop`;
      await new Promise<string>((resolve, reject) => {
      transfer.on('progress', (stats) =>
      console.log(`[${device.id}] Pulled ${stats.bytesTransferred} bytes so far`),
      );
      transfer.on('end', () => {
      console.log(`[${device.id}] Pull complete`);
      resolve(device.id);
      });
      transfer.on('error', reject);
      transfer.pipe(fs.createWriteStream(fn));
      });
      }));
      console.log('Done pulling /system/build.prop from all connected devices');
      } catch (err) {
      console.error('Something went wrong:', err);
      }
      };
    • A convenience shortcut for sync.push(), mainly for one-off use cases. The Sync client is closed automatically.

      Parameters

      • contents: string | Readable

        See sync.push() for details.

      • path: string

        See sync.push() for details.

      • Optionalmode: number

        See sync.push() for details.

      Returns Promise<PushTransfer>

      Pushing a file to all connected devices

      import Adb from '@u4/adbkit';
      const client = Adb.createClient();

      const test = async () => {
      try {
      const devices = await client.listDevices();
      await Promise.all(devices.map(async (device) => {
      const transfer = await device.getClient().push('temp/foo.txt', '/data/local/tmp/foo.txt');
      await new Promise<void>((resolve, reject) => {
      transfer.on('progress', (stats) =>
      console.log(`[${device.id}] Pushed ${stats.bytesTransferred} bytes so far`),
      );
      transfer.on('end', () => {
      console.log(`[${device.id}] Push complete`);
      resolve();
      });
      transfer.on('error', reject);
      });
      }));
      console.log('Done pushing foo.txt to all connected devices');
      } catch (err) {
      console.error('Something went wrong:', err);
      }
      };
    • A convenience shortcut for sync.readdir(), mainly for one-off use cases. The Sync client is closed automatically.

      Parameters

      • path: string

        See sync.readdir() for details.

      Returns Promise<Entry[]>

      File entries list

      List files in a folder

      import Adb from '@u4/adbkit';
      const client = Adb.createClient();

      const test = async () => {
      try {
      const devices = await client.listDevices();
      await Promise.all(devices.map(async (device) => {
      const files = await device.getClient().readdir('/sdcard');
      for (const file of files) {
      if (file.isFile()) {
      console.log(`[${device.id}] Found file "${file.name}"`);
      }
      }
      }));
      console.log('Done checking /sdcard files on connected devices');
      } catch (err) {
      console.error('Something went wrong:', err);
      }
      };
    • A convenience shortcut for sync.readdir64(), mainly for one-off use cases. The Sync client is closed automatically.

      Parameters

      • path: string

        See sync.readdir64() for details.

      Returns Promise<Entry64[]>

      File entries list

    • Attempts to remount the /system partition in read-write mode. This will usually only work on emulators and developer devices.

      Returns Promise<boolean>

      true

    • Remove the port forward at ADB server host (local). This is analogous to adb forward --remove <local>. It's important to note that if you are connected to a remote ADB server, the forward on that host will be removed.

      Parameters

      • local: string

        A string representing the local endpoint on the ADB host.

      Returns Promise<boolean>

      true

    • Reverses socket connections from the device (remote) to the ADB server host (local). This is analogous to adb reverse <remote> <local>.

      Parameters

      • remote: string

        A string representing the remote endpoint on the device.

      • local: string

        A string representing the local endpoint on the ADB host.

      Returns Promise<true>

      true

    • Puts the device into root mode which may be needed by certain shell commands. A remount is generally required after a successful root call. Note that this will only work if your device supports this feature. Production devices almost never do.

      Returns Promise<boolean>

      true

    • Takes a screenshot in PNG format using the built-in screencap utility. Falls back to framebuffer('png') on older Android devices.

      Returns Promise<Duplex>

      The PNG stream.

    • Runs a shell command on the device. Note that you'll be limited to the permissions of the shell user, which ADB uses.

      Parameters

      • command: string | ArrayLike<WithToString>

        The shell command to execute. When String, the command is run as-is. When Array, the elements will be rudimentarily escaped (for convenience, not security) and joined to form a command.

      Returns Promise<Duplex>

      A readable stream (Duplex / Socket) containing the progressive stdout of the command. Use with Adb.util.readAll to read it into a Buffer.

      Read the output of an instantaneous command

      import Adb from '@u4/adbkit';

      try {
      const client = Adb.createClient();
      const devices = await client.listDevices();
      for (const device of devices) {
      const stream = await device.getClient().shell('echo $RANDOM');
      // Use the readAll() utility to read all the content without
      // having to deal with the readable stream. `output` will be a Buffer
      // containing all the output.
      const output = await Adb.util.readAll(stream);
      console.log('[%s] %s', device.id, output.toString().trim());
      }
      console.log('Done.');
      } catch (err) {
      console.error('Something went wrong:', err);
      }

      Progressively read the output of a long-running command and terminate it

      import Adb from '@u4/adbkit';

      const client = Adb.createClient();
      const devices = await client.listDevices();
      for (const device of devices) {
      // logcat just for illustration, prefer device.getClient().openLogcat() in real use
      const conn = await device.getClient().shell('logcat');
      let line = 0;
      conn.on('data', (data) => {
      // here `ps` on the device shows the running logcat process
      console.log(data.toString());
      line += 1;
      // close the stream and the running process
      // on the device will be gone, gracefully
      if (line > 100) conn.end();
      });
      conn.on('close', () => {
      // here `ps` on the device shows the logcat process is gone
      console.log('100 lines read already, bye');
      });
      }
      console.log('Done.');
    • A convenience shortcut for sync.stat(), mainly for one-off use cases. The Sync client is closed automatically.

      Parameters

      • path: string

        The path.

      Returns Promise<Stats>

      A Stats instance (mode, size, mtime).

    • A convenience shortcut for sync.stat64(), mainly for one-off use cases. The Sync client is closed automatically.

      Parameters

      • path: string

        The path.

      Returns Promise<Stats64>

      A Stats64 instance.

    • Establishes a new Sync connection that can be used to push and pull files. This method provides the most freedom and the best performance for repeated use, but can be a bit cumbersome to use. For simple use cases, consider using device.stat(), device.push() and device.pull().

      Returns Promise<Sync>

      The Sync client. Call sync.end() when done.

    • Puts the device's ADB daemon into tcp mode, allowing you to use adb connect or client.connect() to connect to it. Same as adb tcpip <port>.

      Parameters

      • port: number = 5555

        Optional. The port the device should listen on. Defaults to 5555.

      Returns Promise<number>

      The port the device started listening on.

    • Starts a JDWP tracker for the given device.

      Note that as the tracker will keep a connection open, you must call tracker.end() if you wish to stop tracking JDWP processes.

      Returns Promise<JdwpTracker>

      The JDWP tracker (EventEmitter).

    • Get a local TCP port connected to remote socket; tries preferedPort first and falls back to an available port if taken. Note if a forward already exists to the same destination with a different port, no new forward will be created.

      Parameters

      • remote: string

        A string representing the remote endpoint on the device.

      • OptionalpreferedPort: number

        the TCP port you would like to get.

      Returns Promise<number>

      the used port

    • Uninstalls the package from the device. This is roughly analogous to adb uninstall <pkg>.

      Parameters

      • pkg: string

        The package name. This is NOT the APK.

      • Optionalopts: UninstallCommandOptions

        Optional uninstall flags and failure handling (throwOnFailure).

      Returns Promise<boolean>

      true on success, or true on non-DELETE_FAILED_DEVICE_POLICY_MANAGER failures unless opts.throwOnFailure is true (in which case UninstallError is thrown).

    • Puts the device's ADB daemon back into USB mode. Reverses tcpip(). Same as adb usb.

      Returns Promise<boolean>

      true

    • Waits until the device has finished booting. Note that the device must already be seen by ADB.

      Returns Promise<boolean>

      true

    • Waits until ADB can see the device.

      Returns Promise<string>

      The device ID. Can be useful for chaining.