node.js - Express:使用 UglifyJS 从远程 URL 缩小 CSS/JS
问题描述
我设法在#1 上获取数据,但无法在 Express #2 中打印出来,如何解析数据并输出?
我相信这是我的代码错误,我无法放置正确的异步/等待。
这是我的代码:
缩小.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 }
获取.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 }
应用程序.js
const express = require('express');
const { getMinify } = require('./minify');
const app = express();
app.get('/*', getMinify);
app.listen(5000);
解决方案
基于uglify-js,minify(data)
函数的结果有两个对象code
和error
.
并且minify(data)
不需要await
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)更改了 minify.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
}
推荐阅读
- android - 为什么使用 NDK 不能存在不同的 stl 实现?
- swift - 如何在swift中制作带有背景颜色的交叉标签?
- sql - 有没有什么可能的方法可以只做大写的“元音”表单列名=“last_name”?
- python - 执行函数时无法从 AWS 层切换到指定本地构建的可编辑 pip3 包
- angular - 如何控制角垫图标的方向
- javascript - 访问整个输入类型日期值集
- java - 如何在 cassandra 中为 API 实现分页?
- react-native - 如何修复 React Native 中自定义标签栏的行为?
- python-asyncio - 使用 asyncio 完成多项终极工作
- amazon-web-services - 如何在没有任何代码的情况下将来自 websocket 的数据放到亚马逊 kinesis 数据流中(仅通过使用托管 aws 服务)?