Skip to content

Instantly share code, notes, and snippets.

@ViniciusFXavier
Created June 23, 2024 23:19
Show Gist options
  • Save ViniciusFXavier/3ab7fb24351c0f4ca1d3dcdeaa397165 to your computer and use it in GitHub Desktop.
Save ViniciusFXavier/3ab7fb24351c0f4ca1d3dcdeaa397165 to your computer and use it in GitHub Desktop.
[NODE-REALOAD] Update node dependencies without close running server
// On this example i can add or remove routes and no need to stop ou restart the server
const http = require('http');
// nothing before will be updated if there are changes
require('./node-reload') // Does not change the caller file, requiring on the start is best
// any require from here will be updated if there are changes
// Criando o servidor HTTP
const server = http.createServer((req, res) => {
const { routes } = require('./routes/index')
routes(req, res)
});
// Iniciando o servidor na porta 3000
server.listen(3000, () => {
console.log('Server is running on http://localhost:3000 !');
});
const Module = require('module');
const fs = require('fs');
const path = require('path');
const originalRequire = Module.prototype.require;
const watchers = new Map();
function clearCache(filename) {
const resolvedPath = path.resolve(filename);
delete require.cache[resolvedPath];
}
function watchFile(filename) {
const resolvedPath = path.resolve(filename);
if (watchers.has(resolvedPath)) return;
if (fs.existsSync(resolvedPath)) {
const watcher = fs.watch(resolvedPath, (eventType) => {
if (eventType === 'change' || eventType === 'rename') {
// console.log(`Detected change in ${resolvedPath}, reloading...`);
clearCache(resolvedPath);
originalRequire.call(module, resolvedPath);
}
});
watchers.set(resolvedPath, watcher);
}
}
Module.prototype.require = function (filename) {
const resolvedPath = Module._resolveFilename(filename, this);
const req = originalRequire.call(this, filename);
if (![ // Add here if you have any files or folders that you don't want updated
/[\/\\]node_modules[\/\\]/
].some(e => e.test(resolvedPath))) {
watchFile(resolvedPath);
clearCache(resolvedPath);
}
// console.log(`Requiring module: ${resolvedPath}`);
return req;
};
// any update to this file will auto update on server with out closing
const routes = (req, res) => {
if (req.url === '/hello') {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello, World!');
} else if (req.url === '/new') {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('New route!');
} else {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Not Found');
}
}
module.exports = { routes }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment