Skip to content

Instantly share code, notes, and snippets.

@andrei-markeev
Last active November 19, 2024 16:02
Show Gist options
  • Save andrei-markeev/47e5a9728f3961aa46635e19eedd7bdb to your computer and use it in GitHub Desktop.
Save andrei-markeev/47e5a9728f3961aa46635e19eedd7bdb to your computer and use it in GitHub Desktop.
Local NGINX dev server script
const path = require('path');
process.chdir(path.join(__dirname, '..'));
const fs = require('fs');
const child_process = require('child_process');
// replace with your own paths
// you can find the command for the nginxExe by running "which nginx" in the terminal
const nginxExe = '/usr/local/bin/nginx';
const mimeTypes = '/usr/local/etc/nginx/mime.types';
const nginxConf = path.join(__dirname, 'nginx.conf');
const devConf = path.join(__dirname, 'dev.conf');
const htmlRoot = path.join(__dirname, 'dist');
let nginxProcess;
createDevConf();
runNginx();
watchChangesInNginxConf();
function runNginx() {
nginxProcess = child_process.spawn(nginxExe, ['-c', devConf]);
nginxProcess.stdout.on('data', (data) => console.log(data.toString()));
nginxProcess.stderr.on('data', (data) => console.error(data.toString()));
}
function recreateDevConfAndReload() {
console.log('Reload');
createDevConf();
child_process.exec(nginxExe + ' -c ' + devConf + ' -s reload');
}
function watchChangesInNginxConf() {
fs.watchFile(nginxConf, recreateDevConfAndReload);
}
function createDevConf() {
let nginxConfContent = fs.readFileSync(nginxConf, 'utf-8');
let devConfContent = nginxConfContent
.replace(/user ([^\r\n]+)/, '')
.replace(/pid ([^\r\n]+)/, 'daemon off;')
.replace(/worker_processes\s+auto;/, 'worker_processes 1;')
.replace(/include \s+\/etc\/nginx\/mime\.types;/, 'include ' + mimeTypes + ';')
.replace(/error_log [^\r\n]+/, 'error_log /dev/stderr info;')
.replace(/access_log [^\r\n]+/, 'access_log /dev/stdout main;')
.replace(/root\s+\/usr\/share\/nginx\/html;/, 'root ' + htmlRoot + ';');
// add more if needed
fs.writeFileSync(devConf, devConfContent);
}
process.on('SIGTERM', () => {
nginxProcess.stderr.destroy();
nginxProcess.stdout.destroy();
nginxProcess.kill();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment