You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
nodebb/minifier.js

81 lines
1.5 KiB
JavaScript

"use strict";
var uglifyjs = require('uglify-js'),
less = require('less'),
async = require('async'),
fs = require('fs'),
path = require('path'),
11 years ago
crypto = require('crypto'),
utils = require('./public/src/utils'),
Minifier = {
js: {}
};
/* Javascript */
10 years ago
Minifier.js.minify = function (scripts, minify, callback) {
scripts = scripts.filter(function(file) {
return fs.existsSync(file) && file.endsWith('.js');
});
if (minify) {
10 years ago
minifyScripts(scripts, function() {
callback.apply(this, arguments);
});
} else {
10 years ago
concatenateScripts(scripts, callback);
}
};
process.on('message', function(payload) {
switch(payload.action) {
case 'js':
10 years ago
Minifier.js.minify(payload.scripts, payload.minify, function(minified) {
process.send({
type: 'end',
10 years ago
minified: minified
});
});
break;
}
});
10 years ago
function minifyScripts(scripts, callback) {
11 years ago
try {
10 years ago
var minified = uglifyjs.minify(scripts, {
compress: false
}),
11 years ago
hasher = crypto.createHash('md5'),
hash;
// Calculate js hash
hasher.update(minified.code, 'utf-8');
hash = hasher.digest('hex');
process.send({
type: 'hash',
payload: hash.slice(0, 8)
});
10 years ago
callback(minified.code);
11 years ago
} catch(err) {
11 years ago
process.send({
type: 'error',
10 years ago
payload: err.message
11 years ago
});
11 years ago
}
}
10 years ago
function concatenateScripts(scripts, callback) {
async.map(scripts, fs.readFile, function(err, scripts) {
if (err) {
11 years ago
process.send({
type: 'error',
payload: err
11 years ago
});
}
10 years ago
scripts = scripts.join(require('os').EOL + ';');
10 years ago
callback(scripts);
});
}