I am working on a Software Development project using Node.js and I want to automate a specific task by running a local script called "utility.js". Instead of typing node utility.js every time, I want to integrate this into my package.json file. How do I define a custom command in the scripts section, and what is the correct terminal syntax to trigger it? I also need to know if I can pass arguments through NPM to my underlying JavaScript file.
3 answers
Adding a custom script is straightforward. Open your package.json and locate the "scripts" object. You can add a new key-value pair where the key is your command name and the value is the execution string. For example: "my-task": "node utility.js". To run this, you would use npm run my-task in your terminal. This is widely used in Software Development to wrap complex commands—like starting a linter or a test suite—into a single, easy-to-remember word. If your file is in a subfolder, just ensure the path is correct, such as "node ./scripts/utility.js".
Does the npm run command automatically pick up environment variables defined in a .env file, or do I need to use a package like dotenv within my "utility.js" file to access them?
If you need to pass arguments, remember to use the double dash. For example: npm run my-task -- --port 3000. This tells NPM to pass everything after the -- directly to your Node process.
I agree with Margaret. The double dash is a lifesaver when you're building dynamic Software Development tools where you need to change parameters on the fly without editing the package.json file every time.
Steven, NPM doesn't load .env files by default. You have two common options in Software Development: either use the dotenv package at the top of your "utility.js" or use a tool like dotenv-cli in your script definition, like "my-task": "dotenv -e .env node utility.js". Personally, I prefer importing dotenv directly in the code so the script remains portable regardless of how it's called. This ensures your configuration is consistent across different deployment environments.