Skip to content

Instantly share code, notes, and snippets.

@mkober
Created January 6, 2020 04:48
Show Gist options
  • Save mkober/5ffe8ebfa300a02940ccc7d5d48d9533 to your computer and use it in GitHub Desktop.
Save mkober/5ffe8ebfa300a02940ccc7d5d48d9533 to your computer and use it in GitHub Desktop.
Node.js Web Server and Watcher
const connect = require('connect');
const finalhandler = require('finalhandler');
const serveStatic = require('serve-static');
const path = require('path');
const winston = require('winston');
const sassMiddleware = require('node-sass-middleware')
const http = require('http');
const hound = require('hound')
const cpx = require("cpx");
const fs = require('fs');
const pubPath = __dirname + '/public';
const srcPath = __dirname + "/src/**/*.{html,css,js,png,jpg}"
const port = 8080;
const app = connect();
const watcher = hound.watch(pubPath)
function clearDirectory(pubPath, pathTemp = false) {
if (fs.existsSync(pubPath)) {
if (fs.lstatSync(pubPath).isDirectory()) {
var files = fs.readdirSync(pubPath);
if (!files.length)
return fs.rmdirSync(pubPath);
for (var file in files) {
var currentPath = pubPath + "/" + files[file];
if (!fs.existsSync(currentPath))
continue;
if (fs.lstatSync(currentPath).isFile()) {
fs.unlinkSync(currentPath);
continue;
}
if (fs.lstatSync(currentPath).isDirectory() && !fs.readdirSync(currentPath).length) {
fs.rmdirSync(currentPath);
}
else {
clearDirectory(currentPath, pubPath);
}
}
clearDirectory(pubPath);
}
else {
fs.unlinkSync(pubPath);
}
}
if (pathTemp)
clearDirectory(pathTemp);
return true;
}
fs.readdir(pubPath, (err, files) => {
if (err)
throw err;
if (clearDirectory(pubPath));
console.log(pubPath + ' has been cleared');
});
cpx.watch(srcPath, pubPath);
watcher.on('create', function(file, stats) {
console.log(file + ' was created')
}).on('change', function(file, stats) {
console.log(file + ' was changed')
}).on('delete', function(file) {
console.log(file + ' was deleted')
})
app.use(
sassMiddleware({
src: path.join(__dirname,'src/assets/sass'),
dest: path.join(__dirname, 'public/assets/css'),
debug: true,
indentedSyntax: true,
outputStyle: 'expanded',
prefix: '/assets/css',
})
);
app.use(serveStatic(pubPath));
http.createServer(app).listen(port, function() {
console.log('Listening on port ' + port);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment