DEV Community

Cover image for Run gists using npx
Srecko Kostic
Srecko Kostic

Posted on • Edited on • Originally published at faun.pub

Run gists using npx

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

#!/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
// --------------------------------------------------
Enter fullscreen mode Exit fullscreen mode

package.json

{
  "name": "npx-runs-gist",
  "description": "the gist to run it with npx command",
  "version": "0.1.0",
  "bin": "./code.js"
}
Enter fullscreen mode Exit fullscreen mode

run-the-gist.bat

REM this is a comment in .bat files
REM runs the gist on Windows OS

npx https://gist.github.com/srele96/55260739ddef08389a2d992e132c843e
Enter fullscreen mode Exit fullscreen mode

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

#!/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));
Enter fullscreen mode Exit fullscreen mode

package.json

{
  "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"
}
Enter fullscreen mode Exit fullscreen mode

run-the-gist.bat

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 / a/b/c
Enter fullscreen mode Exit fullscreen mode

Top comments (0)