Skip to content

Instantly share code, notes, and snippets.

@rpivo
Last active July 13, 2021 23:59
Show Gist options
  • Save rpivo/7322876fd35fdb12517bb774221f192d to your computer and use it in GitHub Desktop.
Save rpivo/7322876fd35fdb12517bb774221f192d to your computer and use it in GitHub Desktop.
Different Ways to Call a Node Function From the Command Line

Different Ways to Call a Node Function From the Command Line

Separate Initializer in Its Own File

Pros:

  • Main logic file can contain a variety of different functions/processes that don't have to pertain to the function that's being run.
  • Function can easily be called from other scripts, but also directly from the command line.

Cons:

  • Requires extra file.

util.js

export function doThing() {
  console.log("I did a thing");
}

thing.js

import { thing } from './util.js';
thing();
$ node thing.js

Self-Executing Logic

Pros:

  • File is essentially the function. Self-contained execution scope is minimal and simple for command line usage.

Cons:

  • Requires dynamic import if you really want to call it from another module rather than the command line.
  • Can't reasonably ingest arguments or return values.

thing.js

console.log("I did a thing");
$ node thing.js

Single File with Initializer Function

Pros:

  • No "dangling" code. If the file contains a lot of complicated logic, then the "init"/"constructor" initializer function identifies an entry point to the logic.
  • Provides an additional scope to variables that may need to be private within the file.

Cons:

  • Requires dynamic import if you really want to call it from another module rather than the command line.
  • Can't reasonably ingest arguments or return values.
  • Might introduce an unnecessary scope.

thing.js

function init() {
  console.log("I did a thing");
}

init();
$ node thing.js
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment