About
This page shows showcase how to reload a node http server with the watch possibility of gulp
Code
Below is an example of gulp.esm.js file that show case how to do it. You can adapt it to your situation.
// automatically loads when you run the gulp command
import gulp from "gulp";
import {spawn} from "child_process";
import tcpPortUsed from 'tcp-port-used';
// the server process variable
let serverProcess;
// the port
let port = 3000;
export async function server() {
serverProcess = await restartServer(serverProcess);
console.log(`Node server (re)started at http://localhost:${port}:`);
}
// The code that start or restart the process
async function restartServer(serverProcess) {
// kill previous spawned process
if (serverProcess) {
serverProcess.kill();
await tcpPortUsed.waitUntilFree(port, 500, 4000)
console.log('Server process has been terminated');
}
// `spawn` a child `gulp` process linked to the parent `stdio`
serverProcess = spawn('node', ['src/server-start.js', port]);
serverProcess.stdout.on('data', (data) => {
console.log(`Server Stdout: ${data}`);
});
serverProcess.stderr.on('data', (data) => {
console.error(`Server Stderr: ${data}`);
});
return serverProcess;
}
// The default
export default async function () {
await gulp.watch('src/**/*.*', server);
}