refactor: async/await install/web.js

v1.18.x
Barış Soner Uşaklı 4 years ago
parent 1fd2eba6f2
commit 3881ac309f

@ -1,21 +1,26 @@
'use strict'; 'use strict';
var winston = require('winston'); const winston = require('winston');
var express = require('express'); const express = require('express');
var bodyParser = require('body-parser'); const bodyParser = require('body-parser');
var fs = require('fs'); const fs = require('fs');
var path = require('path'); const path = require('path');
var childProcess = require('child_process'); const childProcess = require('child_process');
var less = require('less'); const less = require('less');
var async = require('async'); const util = require('util');
var uglify = require('uglify-es'); const lessRenderAsync = util.promisify(
var nconf = require('nconf'); (style, opts, cb) => less.render(String(style), opts, cb)
var Benchpress = require('benchpressjs'); );
const uglify = require('uglify-es');
var app = express(); const nconf = require('nconf');
var server;
const Benchpress = require('benchpressjs');
var formats = [ const { paths } = require('../src/constants');
const app = express();
let server;
const formats = [
winston.format.colorize(), winston.format.colorize(),
]; ];
@ -42,9 +47,9 @@ winston.configure({
], ],
}); });
var web = module.exports; const web = module.exports;
var scripts = [ const scripts = [
'node_modules/jquery/dist/jquery.js', 'node_modules/jquery/dist/jquery.js',
'node_modules/xregexp/xregexp-all.js', 'node_modules/xregexp/xregexp-all.js',
'public/src/modules/slugify.js', 'public/src/modules/slugify.js',
@ -53,39 +58,39 @@ var scripts = [
'node_modules/zxcvbn/dist/zxcvbn.js', 'node_modules/zxcvbn/dist/zxcvbn.js',
]; ];
var installing = false; let installing = false;
var success = false; let success = false;
var error = false; let error = false;
var launchUrl; let launchUrl;
web.install = function (port) { web.install = async function (port) {
port = port || 4567; port = port || 4567;
winston.info('Launching web installer on port ' + port); winston.info('Launching web installer on port ' + port);
app.use(express.static('public', {})); app.use(express.static('public', {}));
app.engine('tpl', function (filepath, options, callback) { app.engine('tpl', function (filepath, options, callback) {
async.waterfall([ filepath = filepath.replace(/\.tpl$/, '.js');
function (next) {
fs.readFile(filepath, 'utf-8', next); Benchpress.__express(filepath, options, callback);
},
function (buffer, next) {
Benchpress.compileParse(buffer.toString(), options, next);
},
], callback);
}); });
app.set('view engine', 'tpl'); app.set('view engine', 'tpl');
app.set('views', path.join(__dirname, '../src/views')); const viewsDir = path.join(paths.baseDir, 'build/public/templates');
app.set('views', viewsDir);
app.use(bodyParser.urlencoded({ app.use(bodyParser.urlencoded({
extended: true, extended: true,
})); }));
try {
async.parallel([compileLess, compileJS, copyCSS, loadDefaults], function (err) { await Promise.all([
if (err) { compileLess(),
winston.error(err.stack); compileJS(),
} copyCSS(),
loadDefaults(),
]);
setupRoutes(); setupRoutes();
launchExpress(port); launchExpress(port);
}); } catch (err) {
winston.error(err.stack);
}
}; };
@ -180,120 +185,97 @@ function install(req, res) {
}); });
} }
function launch(req, res) { async function launch(req, res) {
res.json({}); try {
server.close(); res.json({});
req.setTimeout(0); server.close();
var child; req.setTimeout(0);
var child;
if (!nconf.get('launchCmd')) {
child = childProcess.spawn('node', ['loader.js'], { if (!nconf.get('launchCmd')) {
detached: true, child = childProcess.spawn('node', ['loader.js'], {
stdio: ['ignore', 'ignore', 'ignore'], detached: true,
}); stdio: ['ignore', 'ignore', 'ignore'],
});
console.log('\nStarting NodeBB');
console.log(' "./nodebb stop" to stop the NodeBB server');
console.log(' "./nodebb log" to view server output');
console.log(' "./nodebb restart" to restart NodeBB');
} else {
// Use launchCmd instead, if specified
child = childProcess.exec(nconf.get('launchCmd'), {
detached: true,
stdio: ['ignore', 'ignore', 'ignore'],
});
}
var filesToDelete = [ console.log('\nStarting NodeBB');
'installer.css', console.log(' "./nodebb stop" to stop the NodeBB server');
'installer.min.js', console.log(' "./nodebb log" to view server output');
'bootstrap.min.css', console.log(' "./nodebb restart" to restart NodeBB');
]; } else {
// Use launchCmd instead, if specified
async.each(filesToDelete, function (filename, next) { child = childProcess.exec(nconf.get('launchCmd'), {
fs.unlink(path.join(__dirname, '../public', filename), next); detached: true,
}, function (err) { stdio: ['ignore', 'ignore', 'ignore'],
if (err) { });
winston.warn('Unable to remove installer files');
} }
const filesToDelete = [
'installer.css',
'installer.min.js',
'bootstrap.min.css',
];
await Promise.all(
filesToDelete.map(
filename => fs.promises.unlink(path.join(__dirname, '../public', filename))
)
);
child.unref(); child.unref();
process.exit(0); process.exit(0);
}); } catch (err) {
winston.error(err.stack);
throw err;
}
} }
function compileLess(callback) { async function compileLess() {
var installSrc = path.join(__dirname, '../public/less/install.less'); try {
fs.readFile(installSrc, function (err, style) { const installSrc = path.join(__dirname, '../public/less/install.less');
if (err) { const style = await fs.promises.readFile(installSrc);
return winston.error('Unable to read LESS install file: ', err.stack); const css = await lessRenderAsync(style, { filename: path.resolve(installSrc) });
} await fs.promises.writeFile(path.join(__dirname, '../public/installer.css'), css.css);
} catch (err) {
less.render(style.toString(), { winston.error('Unable to compile LESS: \n' + err.stack);
filename: path.resolve(installSrc), throw err;
}, function (err, css) { }
if (err) {
return winston.error('Unable to compile LESS: ', err.stack);
}
fs.writeFile(path.join(__dirname, '../public/installer.css'), css.css, callback);
});
});
} }
function compileJS(callback) { async function compileJS() {
var code = ''; let code = '';
async.eachSeries(scripts, function (srcPath, next) {
fs.readFile(path.join(__dirname, '..', srcPath), function (err, buffer) {
if (err) {
return next(err);
}
code += buffer.toString(); for (const srcPath of scripts) {
next(); // eslint-disable-next-line no-await-in-loop
}); const buffer = await fs.promises.readFile(path.join(__dirname, '..', srcPath));
}, function (err) { code += buffer.toString();
if (err) { }
return callback(err); const minified = uglify.minify(code, {
} compress: false,
try {
var minified = uglify.minify(code, {
compress: false,
});
if (!minified.code) {
return callback(new Error('[[error:failed-to-minify]]'));
}
fs.writeFile(path.join(__dirname, '../public/installer.min.js'), minified.code, callback);
} catch (e) {
callback(e);
}
}); });
if (!minified.code) {
throw new Error('[[error:failed-to-minify]]');
}
await fs.promises.writeFile(path.join(__dirname, '../public/installer.min.js'), minified.code);
} }
function copyCSS(next) { async function copyCSS() {
async.waterfall([ const src = await fs.promises.readFile(
function (next) { path.join(__dirname, '../node_modules/bootstrap/dist/css/bootstrap.min.css'), 'utf8'
fs.readFile(path.join(__dirname, '../node_modules/bootstrap/dist/css/bootstrap.min.css'), 'utf8', next); );
}, await fs.promises.writeFile(path.join(__dirname, '../public/bootstrap.min.css'), src);
function (src, next) {
fs.writeFile(path.join(__dirname, '../public/bootstrap.min.css'), src, next);
},
], next);
} }
function loadDefaults(next) { async function loadDefaults() {
var setupDefaultsPath = path.join(__dirname, '../setup.json'); const setupDefaultsPath = path.join(__dirname, '../setup.json');
fs.access(setupDefaultsPath, fs.constants.F_OK | fs.constants.R_OK, function (err) { try {
if (err) { await fs.promises.access(setupDefaultsPath, fs.constants.F_OK | fs.constants.R_OK);
// setup.json not found or inaccessible, proceed with no defaults } catch (err) {
return setImmediate(next); // setup.json not found or inaccessible, proceed with no defaults
if (err.code !== 'ENOENT') {
throw err;
} }
}
winston.info('[installer] Found setup.json, populating default values'); winston.info('[installer] Found setup.json, populating default values');
nconf.file({ nconf.file({
file: setupDefaultsPath, file: setupDefaultsPath,
});
next();
}); });
} }

Loading…
Cancel
Save