Quick tip for node modules

When writing my node modules, I've come to really quite enjoy using Jest for testing (I've written about how I used tap and it's quite similar).

Sometimes however, being able to execute the module on the command line and passing some arbitrary data can be pretty handy, and I've used the following technique on a growing handful of modules I've written.


READER DISCOUNTSave $80 on terminal.training

I've published 38 videos for new developers, designers, UX, UI, product owners and anyone who needs to conquer the command line today.

$19 - only from this link


Exporting to the CLI

I've written a module called bin-to-file. It's an old JS Bin module that takes a bin structure and returns a single HTML string with everything smooshed together.

The module has tests, but I want to be able to quickly test the output using the command line like this:

$ cat __test__/foo.json | node lib/index.js
‣ <html…

In my lib/index.js (the source for the module), right where I'm exporting the function out, my code includes the following lines:

// if the module isn't being required be another module
// and there's something being piped in, then —
if (!module.parent && !process.stdin.isTTY) {
  const stdin = require('fs').readFileSync(0); // 0 = STDIN

And that's it. Now I can use my module on the command line for arbitrary testing.

Posted 12-Apr 2018 under code.

Want more?

Posts, web development learnings & insights, exclusive workshop and training discounts and more, direct to your inbox.

I won't send you any spam, and you can unsubscribe at any time. Powered by ConvertKit

Awesome, thanks so much!

Now you'll need check your email to confirm your subscription.

There was an error submitting your subscription. Please try again.

Your name

Your email address

We use this field to detect spam bots. If you fill this in, you will be marked as a spammer.

I'd like to receive the free command line mini course.Subscribe