Tips for creating Node.js CLI scripts

24 Nov, 2021Node.js

  1. The script should preferably be written in TypeScript and run with ts-node. You don't want to end up wasting 3 hours on a typo in the object key, TypeScript can catch most of those human errors.

  2. The scripts/*.(js|ts) files are supposed to be running directly from the shell. So for reusable modules, better to put them into scripts/utils or scripts/libs.

  3. Avoid importing files from src or other directories, the scripts directory should be self-enclosed. In this way you can separate the dependencies of the scripts to your web apps and cache the dependencies separately.

  4. Avoid running other scripts with exec('npm run *'), exec('node scripts/*'), instead, export the reusable part of the "runee" script and call it programmatically in the "runner" script.

  5. Keep it simple, don't try to accomplish too many tasks in one single script.

  6. Organising the logic in a procedural way, meaning the code flow should be the same as the execution flow.

  7. Don't create step functions that are only to be called once (except for a main function).

  8. Minimise the number of mandatory options, by assigning default values, but at the same time, those values can be overridden by options or env variables. Overall, favour a convention over configuration design principle.

  9. Use commander.js to declare the options, validate the input and set default value etc, DON't handcraft your own arguments parsing logics.

  10. Use yn to parse boolean env variables, and always do if(yn(process.env.*) === true) not if(yn(process.env.*))

  11. Use the execa to execute shell commands.

  12. Don't suppress the colours, Gitlab CI supports colours and font formats, and it makes the logs much more readable. And you're suggested to use chalk or kleur whenever necessary.

  13. Check the process.env.CI to tell if the script is running in CI, no need to add an option for that.

  14. Logging date/time in a more readable format, such as Wed, 10 Nov 2021, 19:26:28 GMT+8. Don't forget to include the timezone if your teams are working in different timezones.

  15. If the script has disruptive consequences, provide a --dry-run option to allow others to preview the side effects.

  16. The scripts in the package.json is only supposed to be used for running locally on the developers' machine. For running the scripts on the CI, use node scripts/*.js or npx ts-node scripts/*.ts instead.

Powered by Gatsby. Theme inspired by end2end.

© 2014-2022. Made withby mdluo.