🎓 A1Learner
🔍
0 of 50 lessons completed

Running It All with One Command

A single command can start every part of the app at once. A runner tool starts the API and the frontend together.

Scripts in package.json

Three scripts share the work between the two servers.

"scripts": {
  "dev": "concurrently \"npm run dev:api\" \"npm run dev:web\"",
  "dev:api": "nodemon server.js",
  "dev:web": "vite"
}

Starting everything

One command starts both servers.

npm run dev

Example

import { spawn } from 'node:child_process';

const serverCode = 'const http = require("http"); const server = http.createServer((req, res) => { res.setHeader("Content-Type", "application/json"); res.end(JSON.stringify([{ title: "Buy milk", done: false }])); }); server.listen(0, () => { console.log("READY " + server.address().port); });';

const child = spawn(process.execPath, ['-e', serverCode], { stdio: ['ignore', 'pipe', 'inherit'] });
let text = '';
child.stdout.on('data', (chunk) => {
  text += chunk;
  if (text.includes('READY')) {
    const port = text.trim().split(' ')[1];
    fetch('http://localhost:' + port + '/api/notes')
      .then((res) => res.text())
      .then((body) => { console.log(body); child.kill(); });
  }
});
setTimeout(() => child.kill(), 5000);

Key points

  • The runner starts the API and the frontend together.
  • Both servers print their output into the same terminal.
  • The frontend talks to the API while both servers run.
  • One Ctrl+C stops both servers at once.

In this example, the script starts a tiny API as a child process. It waits for the READY line that carries the port. It then fetches the notes list and prints the response. The child process is stopped at the end.

Note

The two servers still use different ports.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does one dev command start in a MERN project?