Create a CLI for R with npm

[This article was first published on Colin Fay, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

How to build a CLI for R, with npm.


This blog post was triggered by a discussion on Twitter with Martin
who was looking for a way to build a CLI that launches an RScript.
Here’s a way to do this using npm.

Please note that this blog post won’t teach you how to build the command
line tool, it will quickly go over the way to create a system-wide
command line interface, using npm.

If you want to learn more about building the utility, see this
fantastic series of blog

by Mark Sellor.

Now, the idea is to have a CLI, i.e. a way to launch your utility with:

$ mytool

And that, system-wide.

What you’ll need

  • An R script (script.R) with in it, for example:

<span class="c1">#!/usr/bin/env Rscript --vanilla</span><span class="w">
</span><span class="n">cli</span><span class="o">::</span><span class="n">cat_rule</span><span class="p">(</span><span class="s2">"yeay"</span><span class="p">)</span><span class="w">
</span><span class="n">cli</span><span class="o">::</span><span class="n">cat_bullet</span><span class="p">(</span><span class="n">Sys.time</span><span class="p">())</span><span class="w">
  • npm, which you can get from

Let’s go

Create a new folder, and go inside it.

mkdir cli && cd cli

Create the R Script there.

echo '#!/usr/bin/env Rscript --vanilla' > script.R
echo 'cli::cat_rule("yeay")' >> script.R
echo 'cli::cat_bullet(Sys.time())' >> script.R

Try your script to see if it works:

RScript script.R

Now launch an npm project:

npm init -y

(You can also run it without the -y to interactively add information
to the package.json.)

Now the important part: add a "bin" value in the package.json, with
the name of the bin you want to create, and the path to the script,
relatively to the package file. Here is an example of a package.json
(I removed some elements).

  "name": "cli",
  "version": "1.0.0",
  "description": "CLI example with npm",
  "bin" : {
    "clir" : "./script.R"
  "author": "Colin Fay",
  "license": "MIT"

Install it globally (need sudo rights):

sudo npm link

And, voilà! Open your terminal, and you’re done!

## ── yeay ────────────────────────────────────────────────
## ● 2019-05-22 22:36:29

Other way to go

To leave a comment for the author, please follow the link and comment on their blog: Colin Fay. offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)