refactor code out into 'lib' directory

`===` is usually your friend, but in this case `!!nextDoc` may be better - I'm not sure if the driver explicitly returns `null` or `undefined`, but better to catch both. NodeJS code often uses `null` and `undefined` interchangeably, even though it really shouldn't.