var fs = require('fs'); var path = require('path'); var express = require('express'); var morgan = require('morgan') var ngn4 = require('ngn4'); var config = {port: 8080} var util = require('./util.js'); var scriptMethods = {}; var app = express(); var accessLogStream = fs.createWriteStream(__dirname + '/access.log', {flags: 'a'}); try { config = require("./config.json"); } catch(err) { console.error("Couldn't load config, using defaults."); console.error(JSON.stringify(config, ' ', 4)); } app.use(require('compression')()); app.use(require('cookie-parser')()); app.use(morgan('combined', {stream: accessLogStream})); // Load data var set = new ngn4.NameGeneratorSet(); var dir = path.join(__dirname, 'data'); fs.readdirSync(dir).forEach(function(file) { console.log('Loading ' + file + '...'); set.import(require('./data/' + file), true); }); // Prepare merged data file for client to use. var data = set.export(); var indexFile = null; // Get index.html fs.readFile(path.join(__dirname + '/www-root/index.html'), 'utf8', function (err, data) { if (err) { throw err; } indexFile = data; }); // Load scripts dir = path.join(__dirname, 'scripts'); fs.readdirSync(dir).forEach(function(file) { console.log('Running ' + file + '...'); require('./scripts/' + file)(set, app, data, scriptMethods); }); // Prepare static directories app.use('/js', express.static('www-root/js')); app.use('/css', express.static('www-root/css')); app.use('/img/', express.static('www-root/img')); // Set up index function sendIndexHtml(req, res) { res.header("Content-Type", "text/html; charset=utf-8"); res.end(util.formatTemplate(indexFile, { generatorStyle: scriptMethods.getBackgroundFromCookie(req.cookies), inited: true, initData: scriptMethods.getInitDataFromCookie(req.cookies), genList: scriptMethods.getGeneratorListJsonData() })); } app.get('/index.html', sendIndexHtml); app.get('/', sendIndexHtml); var server = app.listen(config.port, function () { var host = server.address().address; var port = server.address().port; console.log('Server listening at http://%s:%s', host, port); }); process.on("SIGINT", () => process.exit(0)); process.on("SIGTERM", () => process.exit(0));