After adding a couple things to Node-Libvirt one of the maintainers pointed out my original article on Node-Libvirt referenced the old callback style of using the library so I wanted to take a moment to write up a new guide for using Node-Libvirt with promises rather than callbacks. Since my first post offers a fair amount of detail regarding Node-Libvirt in general, I'll limit this one to showing syntax only.


First lets take a look at connecting to the hypervisor using promises. Of the changes, this is the most prominent (in my opinion anyway).


var libvirt = require('libvirt');  
var hypervisorObject = libvirt.hypervisor;

var hypervisor = new hypervisorObject('qemu:///system');

hypervisor.connect(function() {  
    // The hypervisor object is now connected. From here you can do just about any call you want...
    // Like hypervisor.lookupDomainById(1);

You'll probably want to wrap the code you need to access the hypervisor with in the hypervisor.connect() function to ensure the connection has been made before you attempt to communicate with the hypervisor.

Everything Else

It isn't really worth noting each and every function I mentioned originally, but I will give you a couple examples for how things look using promises.

The basic idea is you add Async to the name of the function you want to call, and then use then instead of a callback. For example:

hypervisor.helloWorld(function(callback) {  
    // Old style

hypervisor.helloWorldAsync(arguments).then(function(return_value) {  
    // New style

For real example take a look at a call to getNodeInfo:

hypervisor.getNodeInfoAsync().then(function(nodeStats) {  
    // nodeStats now has the return value from getNodeInfo


Domains use pretty much the same syntax shown above but I'll run through a few examples:

// Lets make a new domain
hypervisor.defineAsync(domainXML).then(function(domain) {  
    // Use domain to access this domain now

    // Now lets restart that domain
    domain.startAsync().then(function() {
        // Domain has been restarted

// Lets lookup a domain with the id 1
hypervisor.lookupDomainByIdAsync(1).then(function(domain) {  
    // Use the domain object to do other stuff

Would you like to know more?

From here, everything looks almost identical to the syntax you see above. Just append Async to the name of the function and use then instead of a callback and you will be good to go.

If there are any specific calls you are interested in seeing please don't hesitate to leave a comment. Most of these calls do have examples in the Node-Libvirt tests. If you are planning on using Node-Libvirt consider following me on Twitter as I intend to document the full Node-Libvirt API in the future.

Thanks for reading!