hgiesel
hgiesel

Reputation: 5658

Have a startup script to NodeJS CLI

How do you add a startup script to the node.js cli? E.g. for requireing modules or setting some options?

EDIT: I'm talking about the server side, i.e. I want to be able to start up the node CLI at any part of my system and have it preload a startup script (similiar to a bashrc) on a global level.

Upvotes: 2

Views: 316

Answers (1)

bren
bren

Reputation: 4334

When I read your post, I realized that the current Node.js REPL sucks! So I made a basic demo of the functionality of your post, and I called it rattle.

Here, I'll explain each line of the code:

#!/usr/bin/env node

This is the shebang, it makes sure that it's run as Node

const repl    = require("repl"),
      vm      = require("vm"),
      fs      = require("fs"),
      path    = require("path"),
      spawn   = require("child_process").spawn,
      package = require("./package");

Import all the packages, you know the drill

function insertFile(file, context) {
  fs.readFile(file, function(err, contents) {
    if (err)
      throw err;
    vm.runInContext(contents, context);
  });
}

I defined function to insert a file into a VM context (which the REPL is)

if (process.argv.includes("--global")) {
  console.log(path.resolve(__dirname, ".noderc"));

Display the location of the global .noderc

/** Hijack the REPL, if asked **/
 } else if (process.argv.length < 3 || process.argv.includes("-i") || process.argv.includes("--interactive")) {

This starts to be the meat of the code. This detects if the user wants to enter REPL mode

  console.log(`rattle v${package.version}`);

  var cmdline = repl.start("> "),
      context = cmdline.context;

Create the repl, with the standard prompt, and get the VM Context

  /** Insert config files **/
  fs.access(localrc = path.resolve(process.cwd(), ".noderc"), function(noLocal) {
    if (!noLocal) {
      insertFile(localrc, context);
    }
  });

Test if there's a local .noderc, if there is insert it into the context

  fs.access(globalrc = path.resolve(__dirname, ".noderc"), function(noGlobal) {
    if (!noGlobal && globalrc !== localrc) {
      insertFile(globalrc, context);

    }
  });

Test for global .noderc, and insert it

} else {
  /** Defer to node.js **/

  var node = spawn("node", process.argv.slice(2));

  node.stdout.pipe(process.stdout);

  node.stderr.pipe(process.stderr);
}

The rest of this just passes the code to node, because it's not REPL stuff

This was fun to write, and hopefully useful to someone.

Good Luck!

Upvotes: 1

Related Questions