npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

shutdown-async

v1.2.3

Published

Asynchronous shutdown handlers for node.js processes.

Downloads

61

Readme

shutdown-async

Asynchronous shutdown handlers for node.js processes.

Example

Consider a database close operation that is an asynchronous function that must be run at shutdown. That shutdown can be invoked by calling process.exit or by pressing ^C.

/**
 * Simulate closing a database in an asynchronous function
 * returning a promise.
 */
function closeDatabase() {
  return new Promise((resolve) => {
    console.log('Closing database...');
    setTimeout(() => {
      console.log('Database closed');
      resolve();
    }, 1000);
  });
}

Now we call that function in our exit handler.

/**
 * Close the database on exit. Note: This will not work correctly
 * as you cannot call asynchronous functions from an exit handler.
 */
process.on('exit', async () => {
  console.log('Shutting down...');
  await closeDatabase();
  console.log('Shutdown');
});

The output on shutdown will be as follows:

Shutting down...
Closing database...

Clearly, this isn't what we want. That is where this module comes in to help. The following is an example of using this module to accomplish the asynchronous database close action.

import { addExitHandler, exitGracefully } from '../shutdown-async.js';

function closeDatabase() {
  return new Promise((resolve) => {
    console.log('Closing database...');
    setTimeout(() => {
      console.log('Database closed');
      resolve();
    }, 1000);
  });
}

addExitHandler(closeDatabase);

When the program is stopped (either by a signal or by calling exitGracefully - discussed below), the output will be as follows:

Closing database...
Database closed

The code for both the non-working and working examples is in the examples folder.

Details

Processes must perform asynchronous tasks on exit (stopping a server or closing a database, for example). These asynchronous tasks cannot be performed by handling the 'exit' event as only synchronous operations are permitted.

This module manages both synchronous and asynchronous exit handlers. An asynchronous exit handler is a function returning a promise. Both exceptions thrown by synchronous exit handlers and promises rejected by asynchronous exit handlers are retained.

The exit handlers are run when an exit signal (SIGINT, SIGTERM, SIGHUP, or SIGBREAK) is received or you call exitGracefully. (Calling process.exit instead of calling exitGracefully will not work as the asynchronous exit handlers will not be called.)

Once all exit handlers have been called, the process.exit method is called with the number of errors encountered as the exit status. This will be zero for a successful shutdown or a positive integer for a shutdown where errors occurred.

An additional feature is that a carriage return (\r) is written to stdout on SIGINT so that the echoed ^C character does not offset any console output on shutdown.

Install

npm install --save shutdown-async

API

import { addExitHandler } from 'shutdown-async';

addExitHandler(handler);
  • Adds the specified handler to the queue. The exit handler can be a synchronous function that can throw an exception or an asynchronous function that returns a promise.
import { exitGracefully } from 'shutdown-async';

exitGracefully();
  • Called automatically on SIGINT, SIGTERM, SIGHUP, or SIGBREAK. Runs the exit handlers in the order they were added and then calls process.exit(count) where count is the number of errors (exceptions thrown or promises rejected) encountered while running the exit handlers. Calling this function from your code is optional but not required.
import { getExitErrors } from 'shutdown-async';

getExitErrors();
  • Returns an array of errors encountered while running the exit handlers. Useful for testing. You need not call this function from your code.

Example

The code in the test.js file serves as an example and is the module run by npm test.

License

MIT License

Copyright (c) 2022 Frank Hellwig

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.