首页 > 解决方案 > Express JS API 在读取 OG 标签时卡住,CPU 使用率达到 100%

问题描述

我有一个使用 Nodejs 和 Express 编写的 API。我正在使用 NPM 包调用open-graph-scraper ( https://www.npmjs.com/package/open-graph-scraper ) 作为服务读取并响应 URL 的 OG 标签。当我使用此 URL 发送请求时,CPU 使用率达到 100%,并且 API 被卡住,直到停止服务器。

此 NPM 包中已提供超时功能,但该功能似乎无法正常工作。它将随机返回超时错误。对于某些尝试,它根本不会发送超时响应。另外,即使我实现了超时功能,它也不会影响 CPU 问题。

import ogs = require('open-graph-scraper');

public scrapeData(req: Request, res: Response): void {
        const main = new MainController();
        try {
            const targetUrl = req.body.url || null;
            const options = { url: targetUrl, timeout: 5000, onlyGetOpenGraphInfo: true };

            ogs(options, (error: any, results: any) => {
                // This returns true or false. True if there was a error. The error it self is inside the results object.
                if (error === true) {
                    main.sendResponse(res, ResponseMessage.DATA_NOT_FOUND, results, false, ResponseCode.DATA_NOT_FOUND);
                } else {
                    if (results.data) {
                        main.sendResponse(res, ResponseMessage.DATA_FOUND, results, false, ResponseCode.DATA_NOT_FOUND);
                    } else {
                        main.sendResponse(res, ResponseMessage.DATA_NOT_FOUND, [], false, ResponseCode.DATA_NOT_FOUND);
                    }
                }
            });

        } catch (ex) {
            logger.error(ex);
            main.sendResponse(res, ResponseMessage.EXCEPTION, ex, false, ResponseCode.EXCEPTION);
        }
    }

这是挂CPU的请求URL http://bit.ly/2YdwvgN

标签: javascriptnode.jsexpressnpm

解决方案


推荐阅读