Beginner Node.js Interview QuestionsBeginnerPractical
Node.js · Question 18
How do you run Node.js scripts?
Direct answer
Run node file.js or npm run script — use node for direct execution, npm scripts for project commands with PATH and env; pass args after -- and set NODE_ENV for environment-specific behavior.
Common execution patterns
- Direct — node src/index.ts (often via tsx/ts-node in dev).
- npm script — npm run dev runs scripts.dev; adds node_modules/.bin to PATH.
- Arguments — node app.js -- --port 4000; process.argv parses flags.
- Shebang — #!/usr/bin/env node on CLI tools makes file executable on Unix.
cli-args.mjs
#!/usr/bin/env node
const args = process.argv.slice(2);
const port = args.includes("--port")
? Number(args[args.indexOf("--port") + 1])
: 4000;
console.log(`Starting on port ${port}`);
// Run: node cli-args.mjs --port 5000
// Or: npm run content:import:interviews -- data/file.json- watch mode — node --watch (Node 18+) restarts on file changes; tsx watch in AceDevHub dev.
- env vars — NODE_ENV=production node dist/index.js; use dotenv in dev (Q48).