Q:

Promise isn't running within process.exit

Here's an example of some synchronous code that just logs hello world.
function syncTest() {
  console.log("hello world");
}

syncTest();
syncTest();
process.on('exit', function() {
  syncTest();
});

//hello world
//hello world
//hello world

This is expected It runs syncTest() twice then on exit once again.
I have the same code below, but with a promise in it instead.
function existsAsync(path) {
  return new Promise(function(resolve) {
    fs.exists(path, resolve);
  });
}

function promiseTest(projectDir) {
  var pkg = path.join(projectDir, "package.json");
  existsAsync(pkg).then(function(exists) {
    console.log("hello world");
  }).catch(function(e) {
    console.log(e.message);
  });
}

var projectDir = process.cwd();
promiseTest(projectDir);
promiseTest(projectDir);
process.on('exit', function() {
  promiseTest(projectDir);
});

//hello world
//hello world

This code with the promise only runs twice, it doesn't run inside the exit event for some strange reason. Is this a quirk of promises? What could be causing this? Am I not using promises the right way?

A:

Quoting from the process's exit event documentation,

Emitted when the process is about to exit. There is no way to prevent the exiting of the event loop at this point, and once all exit listeners have finished running the process will exit. Therefore you must only perform synchronous operations in this handler. This is a good hook to perform checks on the module's state (like for unit tests). The callback takes one argument, the code the process is exiting with.
Example of listening for exit:
process.on('exit', function(code) {
  // do *NOT* do this
  setTimeout(function() {
    console.log('This will not run');
  }, 0);
  console.log('About to exit with code:', code);
});

So, don't use promises in the exit event handler, instead make your code synchronous.

