Created
April 3, 2020 13:39
-
-
Save jamestthompson3/97f824d21c55d034f1d3e22bc6720b3f to your computer and use it in GitHub Desktop.
Recursively watch files in a project and restart process on change.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"use strict"; | |
const fs = require("fs"); | |
const cluster = require("cluster"); | |
/* | |
* GET IT ALL RUNNING | |
*/ | |
if (cluster.isMaster) { | |
cluster.setupMaster({ | |
exec: "src/server.js" | |
}); | |
cluster.fork(); | |
watchChanges(); | |
} | |
/* | |
* NODEMON LITE | |
*/ | |
async function watchChanges() { | |
const dir = await fs.promises.opendir("src"); | |
await walkRecursive(dir); | |
} | |
async function walkRecursive(dir) { | |
for await (const dirent of dir) { | |
if (dirent.isFile()) { | |
watchFile(dirent.name, dir.path); | |
} else { | |
const recDir = await fs.promises.opendir(`${dir.path}/${dirent.name}`); | |
walkRecursive(recDir); | |
} | |
} | |
} | |
function watchFile(name, path) { | |
fs.watch(`${path}/${name}`, (eventType, fileName) => { | |
if (fileName !== "index.js" && eventType === "change") { | |
for (const id in cluster.workers) { | |
const worker = cluster.workers[id]; | |
worker.kill("SIGTERM"); | |
} | |
cluster.setupMaster({ | |
exec: "src/server.js" | |
}); | |
cluster.fork(); | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment