1

I have written a CLI in Node.js, that you can globally install using npm. Now I want to run a specific piece of code the first time a user runs my CLI. But it should only run once.

My question is: How could I detect that the CLI is run for the very first time?

Of course, I could write a file into the user's home directory, and if it exists, skip code execution. This would be pretty simple.

But now things get slightly more complicated: I want this check to be re-run when the user updates the CLI to a new version. So, again, I could write a file into the user's home directory, and store the versions in it, for which I have run the "once"-code block.

But this again means that every time the user runs the CLI it has to open the file, parse it, look for the version, and so on. I fear that this could negatively impact startup performance.

Is there a better way to solve this?

Golo Roden
  • 140,679
  • 96
  • 298
  • 425

1 Answers1

1

I have a stupid idea, treat this as an academic example of hacky metaprogramming. Create a script named script.js:

var fs = require('fs');

if(!process.env.firstRun){
  var content = fs.readFileSync("script.js", "utf8");
  fs.writeFileSync('script.js', 'process.env.firstRun=true;\r\n' + content, 'utf8');
  console.log('first run');
} else {
  console.log('next run');
}

The script simply overwrites itself by adding an additional flag declaration at the beginning if it's not set. Otherwise it goes the other path:

λ node .\script.js
first run

λ node .\script.js
next run

λ node .\script.js
next run

The above was just for fun. For production code you should go for a configuration file as you proposed. Reading single small file is not a big deal, according to this method it takes <0.5ms in my setup (I5 processor, SSD drive), so it's definitely a way to go.

jedzej
  • 422
  • 3
  • 12