repost: Run gists using npx - DEV Community

We can run gists using npx. I learned about that after reading this: https://nodejs.dev/learn/the-npx-nodejs-package-runner.

# I want to run my gist

I created a gist that prints some text. I ran the command, but it didn’t work. I figured I needed package.json, so I added it and ran it, but it still didn’t work. I remembered I needed a shebang comment and bin property. After adding those and running it, it worked. Here is the full gist:

code.js

1
2
3
4
5
6
7
8
9
10
11
12
#!/usr/bin/env node

console.log("Does that even work?");

// --------------------------------------------------
// To let npx run the gist we need
//
// - package.json
// - shebang comment at the top of file
// - https://en.wikipedia.org/wiki/Shebang_(Unix)
// - bin property in package.json
// --------------------------------------------------

package.json

1
2
3
4
5
6
{
"name": "npx-runs-gist",
"description": "the gist to run it with npx command",
"version": "0.1.0",
"bin": "./code.js"
}

run-the-gist.bat

1
2
3
4
REM this is a comment in .bat files
REM runs the gist on Windows OS

npx https://gist.github.com/srele96/55260739ddef08389a2d992e132c843e

# Use library in the gist

Armed with knowledge, I wanted to use a library. It was straightforward. I copy pasted the example from https://www.npmjs.com/package/commander. Afterward, I ran it, and it worked. Much less effort this time. Here is the full gist:

split.js

1
2
3
4
5
6
7
8
9
10
11
#!/usr/bin/env node

const { program } = require("commander");

program.option("--first").option("-s, --separator <char>");

program.parse();

const options = program.opts();
const limit = options.first ? 1 : undefined;
console.log(program.args[0].split(options.separator, limit));

package.json

1
2
3
4
5
6
7
8
9
{
"name": "split",
"version": "0.1.0",
"description": "run split example from commander docs using gist and npx",
"dependencies": {
"commander": "9.4.0"
},
"bin": "./split.js"
}

run-the-gist.bat

1
2
3
4
5
6
7
8
REM intentionally misspeleld --fits
npx https://gist.github.com/srele96/c4e645abd50c0b3c2e543c8557c044c9 -s / --fits a/b/c

REM uses the correct flag --first
npx https://gist.github.com/srele96/c4e645abd50c0b3c2e543c8557c044c9 -s / --first a/b/c

REM no flag
npx https://gist.github.com/srele96/c4e645abd50c0b3c2e543c8557c044c9 -s /
Edited on