Run a command using sudo, prompting the user with an OS dialog if necessary
npx @tessl/cli install tessl/npm-sudo-prompt@9.2.0sudo-prompt is a cross-platform Node.js library that enables applications to execute terminal commands with elevated privileges (sudo) through native OS dialogs. It supports macOS, Linux, and Windows, automatically presenting the appropriate authentication dialog without requiring external dependencies or native bindings.
npm install sudo-promptconst sudo = require('sudo-prompt');ES6/TypeScript:
import * as sudo from 'sudo-prompt';const sudo = require('sudo-prompt');
const options = {
name: 'MyApp',
icns: '/path/to/icon.icns', // macOS only
env: { 'MY_VAR': 'value' }
};
sudo.exec('echo hello', options, (error, stdout, stderr) => {
if (error) throw error;
console.log('stdout: ' + stdout);
});Executes a terminal command with elevated privileges using OS native authentication dialogs.
/**
* Execute a command using sudo with OS native authentication dialog
* @param {string} command - The command to execute (must not start with "sudo")
* @param {object|function} [options] - Configuration options object, or callback function
* @param {string} [options.name] - Application name for dialog (max 70 chars, alphanumeric + spaces)
* @param {string} [options.icns] - Path to icon file (macOS only, .icns format)
* @param {object} [options.env] - Environment variables to set
* @param {function} [callback] - Callback function (error, stdout, stderr) => void
* @returns {void}
*/
function exec(command, options, callback);
// Alternative signatures:
function exec(command, callback);
function exec(command, options);Usage Examples:
const sudo = require('sudo-prompt');
// Basic usage with callback
sudo.exec('ls /root', (error, stdout, stderr) => {
if (error) throw error;
console.log(stdout);
});
// With options
const options = {
name: 'File Manager',
icns: '/Applications/MyApp.app/Contents/Resources/app.icns'
};
sudo.exec('mkdir /usr/local/myapp', options, (error, stdout, stderr) => {
if (error) {
console.error('Failed to create directory:', error.message);
return;
}
console.log('Directory created successfully');
});
// With environment variables
sudo.exec('echo $MY_CUSTOM_VAR', {
name: 'Environment Test',
env: { 'MY_CUSTOM_VAR': 'hello world' }
}, (error, stdout, stderr) => {
console.log('Environment variable output:', stdout.trim());
});
// Fire-and-forget (no callback)
sudo.exec('touch /tmp/sudo-test', { name: 'Test App' });Configuration object for customizing the sudo execution behavior.
/**
* @typedef {Object} Options
* @property {string} [name] - Application name displayed in the authentication dialog
* @property {string} [icns] - Path to icon file for the dialog (macOS only, .icns format)
* @property {Object.<string, string>} [env] - Environment variables to set for command execution
*/Validation Rules:
name: Must be alphanumeric with spaces allowed, maximum 70 characters. Defaults to process.title if validicns: Must be a non-empty string pointing to a valid .icns file (macOS only)env: Object with string keys and values, keys must be valid POSIX environment variable names (start with letter/underscore, contain only letters/digits/underscores), values cannot contain newlinesThe callback function receives specific error types for different failure conditions.
/**
* Callback function signature for sudo.exec
* @callback CallbackFunction
* @param {Error|undefined} error - Error object or undefined if successful
* @param {string|Buffer|undefined} stdout - Command output or undefined
* @param {string|Buffer|undefined} stderr - Command error output or undefined
*/Common Errors:
"User did not grant permission." - User denied authentication"No polkit authentication agent found." - Linux polkit agent missing"Platform not yet supported." - Unsupported operating system"Command should not be prefixed with \"sudo\"." - Invalid command format"Wrong number of arguments." - Invalid function arguments (must be 1-3 arguments)"Command should be a string." - Command parameter is not a string"Expected options or callback." - Second argument is neither options object nor callback function"Expected options to be an object." - Options parameter is not an object"Expected callback to be a function." - Callback parameter is not a function"process.title cannot be used as a valid name." - Default process.title is invalid"options.name must be alphanumeric only (spaces are allowed) and <= 70 characters." - Invalid name format"options.icns must be a string if provided." - icns is not a string"options.icns must not be empty if provided." - icns is empty string"options.env must be an object if provided." - env is not an object"options.env must not be empty if provided." - env is empty object"options.env environment variables must be strings." - env contains non-string values"options.env has an invalid environment variable name" - env key doesn't match POSIX pattern"options.env has an invalid environment variable value" - env value contains newlinesError Handling Example:
sudo.exec('rm -rf /important/directory', { name: 'Cleanup Tool' }, (error, stdout, stderr) => {
if (error) {
switch (error.message) {
case 'User did not grant permission.':
console.log('User cancelled the operation');
break;
case 'No polkit authentication agent found.':
console.log('Please install a polkit authentication agent');
break;
default:
console.error('Command failed:', error.message);
if (error.code) {
console.error('Exit code:', error.code);
}
}
return;
}
console.log('Command completed successfully');
if (stdout) console.log('Output:', stdout);
if (stderr) console.log('Errors:', stderr);
});.app bundle with AppleScript for authenticationoptions.icns (must be .icns format)pkexec (preferred) or kdesudo for authentication/usr/bin/kdesudo, /usr/bin/pkexecsudo timestamp settingschild_process.exec(), this function does not return a child process objectoptions.env