Created
September 2, 2019 09:54
-
-
Save mreis1/d9a5795ecccc65e08c2343bcbf50de14 to your computer and use it in GitHub Desktop.
node-graceful-sample
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// _ __ _ _ _ | |
// _ __ ___ __| | ___ __ _ _ __ __ _ ___ ___ / _|_ _| | | |_ ___ ___| |_ | |
// | '_ \ / _ \ / _` |/ _ \_____ / _` | '__/ _` |/ __/ _ \ |_| | | | |_____| __/ _ \ __| __| | |
// | | | | (_) | (_| | __/_____| (_| | | | (_| | (__ __/ _| |_| | |_____| |_ __\__ \ |_ | |
// |_| |_|\___/ \__,_|\___| \__, |_| \__,_|\___\___|_| \__,_|_| \__\___|___/\__| | |
// |___/ * | |
// This examples shows that noce-graceful can be used across the project with no issues | |
// We can attach multiple listeners, the app will quit once all listeners are resolved. | |
// We can do this by calling done() ---> registerWithSetTimeout | |
// or we can do this by returning a promise ---> registerWithPromise | |
// | |
// To start: node index.js | |
// Do ctrl + C to quit | |
// | |
// | |
/** | |
* @type {{Graceful} | Graceful} | |
*/ | |
var Graceful = require('node-graceful'); | |
var http = require('http'); | |
process.on('exit', function(){ | |
console.log('exit'); | |
}); | |
let delay = function (duration) { | |
return new Promise(((resolve) => { | |
setTimeout(() => { | |
resolve() | |
}, duration) | |
})) | |
}; | |
let id = 0; | |
let registerWithSetTimeout = function (name, duration) { | |
Graceful.on('exit', async function (done, event, signal) { | |
id++; | |
console.log({ | |
name, id, event, signal | |
}); | |
setTimeout(() => { | |
console.log('Done with ' + name); | |
done(); | |
}, duration) | |
}) | |
}; | |
let registerWithPromise = function (name, duration) { | |
Graceful.on('exit', async function (done, event, signal) { | |
id++; | |
console.log({ | |
name, id, event, signal | |
}); | |
await delay(duration); | |
console.log('Done with ' + name) | |
}) | |
}; | |
registerWithSetTimeout('Calling done() method', 3000); | |
registerWithPromise('Returning a promise ', 5000); | |
var server = http.createServer(); | |
server.listen(5000); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment