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

execifmain

v0.0.2

Published

`execIfMain` helps you gradually create more modular and reusable Node.js scripts that can be used as both libraries and executables.

Downloads

2

Readme

execIfMain

execIfMain helps you gradually create more modular and reusable Node.js scripts that can be used as both libraries and executables.

Basic usage

If foo.js contains

const { execIfMain } = require('execifmain');

export function foo() { … }
function main() { … }

execIfMain(main, module);

then execIfMain will only run main() if foo.js is the main script called with node foo.js.

If foo.js is only being loaded because some other code does require("foo") to use it as a library or run some tests against it, main() won’t run.

In ESM code, pass import.meta instead of module:

import { execIfMain } from 'execifmain';

export function foo() { … }
function main() { … }

execIfMain(main, import.meta);

Why

Doing this is common in many programming languages. Python has its if __name__ == '__main__': idiom, Ruby has if __FILE__ == $PROGRAM_NAME, Java lets you put a static main() method in any class, and there are even idioms for shell scripts.

While Node.js does have if (require.main === module), the extra code needed to handle promises, return codes, and ES modules all mean that your code can be much simpler while handling more edge cases if you delegate that work to this package which encapsulates the required logic.

For an example of where if (require.main === module) breaks down, in Node <= 14 the following code prints a warning but exits with a return code of zero.

async function main() {
  throw new Error("oops");
}
if (require.main === module) {
  main();
}

While you could add a .catch(…) handler that calls console.error() and process.exit(), calling execIfMain is shorter and will do a better job.

Features

Supports async main functions

You can use execIfMain with async functions. execIfMain will set up a catch() handler to exit with error code 1 on promise rejection.

const { execIfMain } = require('execifmain');

async function main() { … }

execIfMain(main, module);

Return values becomes exit codes

If execIfMain runs a function that returns a number, that number becomes the exit code of the process. This also works for async code that returns a promise that resolves to a number.

That means that this code:

import { execIfMain } from 'execifmain';

function main() {
    ⋮
    if (!options.valid()) {
        options.print_help();
        return 64; // EX_USAGE from sysexits(3)
    }
    ⋮
}

execIfMain(main, import.meta);

will return error code 64 to the shell on invalid options.

Run alternate code if not main

execIfMain returns false if it does not run the provided function, allowing you to take extra actions when in library mode.

import { execIfMain } from 'execifmain';

function main() { … }

execIfMain(main, import.meta) || doLibraryModeSpecificInitialization();

Things not yet supported

execIfMain is known not to detect that it should exec main when parcel v1 is used to create bundled script files, as in parcel build --target=node main.js.

Other bundlers have not been tested and are expected not to work yet.

Internal development notes

Some things to know if coding on the execIfMain project itself:

  • enable debug output with DEBUG=execifmain

  • The integration test uses the compiled file, so make sure you are running yarn babel:watch.