How to open various desktop applications from nodejs

The most commonly opened resources in a program are files, urls and database connections. he ‘Opn’ package allows you to open stuff like websites, files, executables in their respective desktop applications. The package is cross-platform.

I usually use the package during testing phase – opening various resources, mostly images and text files after execution of a program.

Installation is via npm.


$ npm install opn

Using opn

As said earlier ‘opn’ allows you to open a URL, file, or executable in their respective desktop applications from within nodejs. The general format of the function is given below.

opn(resource, {app: 'application', 'options']});

A few example are given below.

const opn = require('opn');

// Opens the url in the default browser

// Opens a image in the default system image viewer

// Opens a image in the specified image viewer (on Windows)
opn('samblogger.jpg',{app: 'mspaint'});

// Opens the url in the specified browser with additional options
opn('', {app: ['chrome', '--incognito']});

As you can see you can specify the app to open the target with, or an array with the app and its arguments. Note that the app name is platform dependent. So do not hard code the name in reusable modules. For example, Chrome is ‘google chrome’ on macOS, ‘google-chrome’ on Linux and ‘chrome’ on Windows. (So you will need to change the app name values in the above examples accordingly).

Checking for spawned process

The function returns a promise for the spawned child process. Sometimes it can be useful if you’d like to attach custom event listeners or perform other operations directly on the spawned process.

In the example below when the ‘mspaint’ application closes the ‘exited’ message is shown in the console. You can do additional processing here if required.

opn('samblogger.jpg',{app: 'mspaint'}).then(() => {
    // image viewer closed

The ‘wait’ option specifies if the nodejs program should wait for the opened app to exit before fulfilling the promise – default is ‘true’. If false it’s fulfilled immediately when opening the app. On Windows you have to explicitly specify an app for it to be able to wait.

// Do not wait for the 'mspaint' app to close to fulfill the promise
opn('samblogger.jpg',{wait: false, app: 'mspaint'}).then(() => {

Leave a Reply

Your email address will not be published.