Optionaloptions: Partial<DeviceClientOptions>a DeviceClientExtra
Reattaches ADB to the device's ADB USB interface. This re-enables communication between ADB and device, reversing detach().
true
Execute a service call command and return the Parcel response data as a ParcelReader.
Checks whether a given system service is registered.
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>.
The package name. This is NOT the APK.
true
Detaches ADB's USB interface from ADB. This releases the device from ADB control, allowing other processes to use it.
true
Execute a single command and get stdout response as a Buffer or string.
the command to execute
Execute a single command and get stdout response as a Buffer or string.
the command to execute
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.
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>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>
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.
The desired output format. Defaults to 'raw' for raw framebuffer data.
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.
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').
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.
Optionaliface: string = 'wlan0'
The network interface. Defaults to 'wlan0'.
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.
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
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.
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.
Optional flags passed to ps.
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.
The serial number of the device.
Retrieves the list of available system services.
An AdbServiceInfo array.
Gets the state of the device identified by the given serial number.
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.
When String, interpreted as a path to an APK file. When Readable, installs directly from the stream, which must be a valid APK.
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.
The path to the APK file on the device. The file will be removed when the command completes.
true
Call ip route command. Pass each argument separately, e.g. ipRoute('list', 'table', 'all').
An IpRouteEntry array.
Call ip rule command. Pass each argument separately.
An IpRuleEntry array.
Tells you if the specific package is installed or not. This is analogous to adb shell pm path <pkg> and some output parsing.
The package name. This is NOT the APK.
true if the package is installed, false otherwise.
Lists forwarded connections on the device. This is analogous to adb forward --list.
An array of forward objects with serial, local, and remote.
List packages installed on the device.
Optionaloptions: { thirdparty?: boolean }
list all or only third-party apps
an array of DevicePackage
Lists reversed connections on the device. This is analogous to adb reverse --list.
An array of Reverse objects with remote and local.
List available video encoders on this device. Parses Android's media_codecs configurations.
Prepare a minicap server; this server must be started with start().
Optionaloptions: Partial<MinicapOptions>Opens a direct connection to a unix domain socket in the given path.
The path to the socket. Prefixed with 'localfilesystem:' by default, include another prefix (e.g. 'localabstract:') in the path to override.
The connection (Duplex). Call conn.end() to end the connection.
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().
The name of the log. Available logs include 'main', 'system', 'radio' and 'events'.
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.
Optional. Set clear: true to clear logcat before opening the reader.
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.
Optional. The device port where you'd like Monkey to run at. Defaults to 1080.
The Monkey client.
Tracks /proc/stat and emits CPU load calculations once per second.
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.
The port number to connect to.
Optionalhost: string
Optional. The host to connect to.
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.
See sync.pull() for details.
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.
See sync.push() for details.
See sync.push() for details.
Optionalmode: number
See sync.push() for details.
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.
See sync.readdir() for details.
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.
See sync.readdir64() for details.
File entries list
Record screen video directly using Scrcpy.
Destination file path (.mp4, .h264, .h265, etc.)
OptionalscrcpyOptions: Partial<ScrcpyOptions>
Scrcpy server configuration (videoCodec, maxFps, maxSize, etc.)
OptionalrecordOptions: VideoRecordOptions
Recording control (durationMs, maxFrames, remuxMp4, signal, onProgress)
Attempts to remount the /system partition in read-write mode. This will usually only work on emulators and developer devices.
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.
A string representing the local endpoint on the ADB host.
true
Reverses socket connections from the device (remote) to the ADB server host (local). This is analogous to adb reverse <remote> <local>.
A string representing the remote endpoint on the device.
A string representing the local endpoint on the ADB host.
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.
true
Prepare a Scrcpy server; this server must be started with start().
Optionaloptions: Partial<ScrcpyOptions>Takes a screenshot in PNG format using the built-in screencap utility. Falls back to framebuffer('png') on older Android devices.
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.
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.
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.');
Starts the configured activity on the device. Roughly analogous to adb shell am start <options>.
The activity configuration.
Starts the configured service on the device. Roughly analogous to adb shell am startservice <options>.
The service configuration.
A convenience shortcut for sync.stat(), mainly for one-off use cases. The Sync client is closed automatically.
The path.
A Stats instance (mode, size, mtime).
A convenience shortcut for sync.stat64(), mainly for one-off use cases. The Sync client is closed automatically.
The path.
A Stats64 instance.
Prepare an STFService and STFagent; this server must be started with start().
Optionaloptions: Partial<STFServiceOptions>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().
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>.
Optional. The port the device should listen on. Defaults to 5555.
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.
The JDWP tracker (EventEmitter).
Return a new connection bound to the current device transport.
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.
A string representing the remote endpoint on the device.
OptionalpreferedPort: number
the TCP port you would like to get.
the used port
Uninstalls the package from the device. This is roughly analogous to adb uninstall <pkg>.
The package name. This is NOT the APK.
Optionalopts: UninstallCommandOptions
Optional uninstall flags and failure handling (throwOnFailure).
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.
true
Waits until the device has finished booting. Note that the device must already be seen by ADB.
true
Waits until ADB can see the device.
The device ID. Can be useful for chaining.
Get extra helper functions.