Express:使用UglifyJS从远程URL最小化CSS/JS



我设法在#1上获得了数据,但无法在Express#2中打印出来,如何解析数据并输出?

我相信这是我的代码错误,我无法放置正确的async/await。

这是我的代码:

minimy.js

const { getContent } = require('./get');
const { minifyJS } = require('./processing');
async function getMinify(req, res) {
try {
const remoteUrl = 'http://example.com/script.js';
console.log('URL: ' + remoteUrl);
// #1
const content = await getContent(remoteUrl);
// #2
const outputJS = await minifyJS(content);
res.end(outputJS);
} catch (error) {
res.end(error.content);
}
}
module.exports = { getMinify }

get.js

const got = require('got');
async function getContent(remoteUrl) {
const code = await got(remoteUrl);
return code.body;
}
module.exports = { getContent }

处理.js

const { minify } = require('uglify-js');
async function minifyJS(data) {
const result = await minify(data);
return result.code;
}
module.exports = { minifyJS }

app.js

const express = require('express');
const { getMinify } = require('./minify');
const app = express();
app.get('/*', getMinify);
app.listen(5000);

基于uglify-js,minify(data)函数的结果有两个对象codeerror

CCD_ 4不需要CCD_ 5

processing.js应更改

const { minify } = require("uglify-js");
async function minifyJS(data) {
let { error, code } = minify(data);
if (error) 
throw error;

return code;
}
module.exports = { minifyJS };

以及用于处理两个.js文件(get.js和processing.js(的更改minimy.js

try {
const remoteUrl = 'http://example.com/script.js';
console.log('URL: ' + remoteUrl);
// #1
const content = await getContent(remoteUrl);
// #2
const outputJS = await minifyJS(content);
res.end(outputJS);
} catch (error) {
res.end(error); // remove .content
}

最新更新