首页 > 解决方案 > nodejs express 应用程序中的高堆使用率

问题描述

我是 Nodejs 的新手。我创建了一个脚本,它将文件上传到服务器。当我尝试使用“pm2 start app.js”运行时。我得到活动句柄 - 4,堆使用率超过 80%,而没有运行任何请求。有人可以建议遵循指南以避免此类问题以及如何使其可扩展。我尝试使用 chrome 开发工具拍摄堆快照。却无法理解。

Snapshot1 - 7.3MB(没有点击任何请求)

快照 2 - 13MB(达到 8-9 个请求)

system / JSArrayBufferData×2 - 37 % (浅尺寸)

应用程序.js

const express = require('express');
const fileUpload = require('express-fileupload');
const cors = require('cors');
const bodyParser = require('body-parser');
const morgan = require('morgan');
const _ = require('lodash');

const app = express();

const config = require('./config');
const { HTTP_PORT } = config.env;
const { filesize , audiosize, uploadfilepath, uploadaudiopath} = config.file;

var http = require('http');
var fs = require('fs');
var path = require('path')

// enable css and js
app.use(express.static(path.join(__dirname, '/public')));


// enable files upload
app.use(fileUpload({
    createParentPath: true,
}));

//add other middleware
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(morgan('dev'));

app.post('/upload/file', async (req, res) => {
    try {
        if(!req.files) {
            res.send({
                status: false,
                message: 'No file uploaded'
            });
        } else {
            //Use the name of the input field (i.e. "avatar") to retrieve the uploaded file
            let avatar = req.files.file_upload;
            let id = req.body.userid;
            id = (id === undefined) ? "default" : id;

            // Checking File Size (Max Size - 5MB)
            if(avatar.size > filesize){
        
                return res.send({
                    status: 413,
                    message: 'file size greater than 5mb'
                });
            }
            
            //Use the mv() method to place the file in upload directory (i.e. "uploads")
            try {
                avatar.mv(uploadfilepath +`/${id}_` + avatar.name);
            } catch (error) {
                console.log(error);
                return res.send({
                    status: 413,
                    message: "file couldn't be uploaded"
                });
            }
            
            //send response
            res.send({
                status: true,
                message: 'File is uploaded',
            });
        }
    } catch (err) {
        console.log(err);
        res.status(500).send(err);
    }
});

http.createServer(app).listen(HTTP_PORT, () => 
console.log(`HTTP App is listening on port ${process.env.HTTP_PORT}`));

标签: javascriptnode.jsexpressmemory-leaksheap-memory

解决方案


推荐阅读