Electron中用node-command-line调用adb devices打包后报错
Hey there! I totally get how frustrating this can be—things work smoothly in development but break as soon as you package the app. Let's break down why this is happening and walk through solutions to fix it.
Why does this happen?
When you run npm start, your Electron app inherits all the environment variables from your terminal session—including your full PATH which includes the directory where adb is installed. But when you package with electron-builder, the app launches as a standalone process, and its default PATH is way more restricted. It doesn't automatically include paths like /usr/local/bin or your Android SDK platform-tools folder, so it can't locate the adb command anymore.
Solutions to try:
1. Use the absolute path to adb
Instead of relying on the system PATH, just use the full, direct path to your adb executable. First, find where adb lives by running this in your terminal:
which adb
You'll get a path like /usr/local/bin/adb or ~/Library/Android/sdk/platform-tools/adb. Update your code to use this absolute path:
var cmd = require('node-command-line'); // Replace with the path you got from `which adb` const adbFullPath = '/usr/local/bin/adb'; cmd.run(`${adbFullPath} devices`) .then(output => console.log(output)) .catch(error => console.error(error));
2. Add the adb directory to your app's PATH
If you don't want to hardcode the path (in case users have adb in different locations), modify the PATH environment variable in your Electron main process before running commands:
const { app } = require('electron'); var cmd = require('node-command-line'); app.on('ready', () => { // Add the directory containing adb to the app's PATH const adbDirectory = '/usr/local/bin'; // Or your Android SDK platform-tools path process.env.PATH = `${adbDirectory}:${process.env.PATH}`; // Now run your adb command cmd.run('adb devices') .then(output => console.log(output)) .catch(error => console.error(error)); });
For extra robustness, you could even add a file picker to let users select their adb path if the default locations don't work.
3. Specify the shell for command execution
Sometimes command-line libraries use a minimal shell by default. Try explicitly telling node-command-line to use your system's full shell (like bash or zsh):
var cmd = require('node-command-line'); cmd.run('adb devices', { shell: '/bin/bash' }) .then(output => console.log(output)) .catch(error => console.error(error));
This ensures the command runs in an environment that has access to your full system PATH.
内容的提问来源于stack exchange,提问作者Abhay Kumar Behki

