javascript - Node.js 错误 "terminate called after throwing an instance of ' std::bad_alloc' what(): std::bad_alloc"

标签 javascript c++ node.js

我在 digital ocean 上使用 node.js 并尝试运行文件上传/下载服务器。

为了确保服务器在后台运行并且不会因错误而退出,我使用了以下内容

nohup nodejs server.js &

我正在使用 nodejs 而不是 node 命令,因为这是 digital ocean 推荐的。
该服务器几乎专用于上传和下载文件。这适用于大约两个文件,但随后服务器崩溃并出现以下错误:

“在抛出 'std::bad_alloc' what(): std::bad_alloc 实例后调用终止”

我不知道是什么原因造成的,如果有任何帮助,我将不胜感激。防止崩溃会很好,但也能让 Node 服务器不会崩溃也很好。我认为这就是 nohup 所做的,但显然不是。 (我也无法永远正常工作)。

这是我的服务器的代码:

var http = require('http'),
    url = require('url'),
    util = require('util'),
    path = require('path'),
    fs = require('fs'),
    qs = require('querystring');


var formidable = require('formidable'),
    mime = require('mime');
var account = {username: 'test', password: 'etc'};
var accounts = [account],
    port = 9090,




function dirTree(filename) {
    var stats = fs.lstatSync(filename),
        info = {
            name: path.basename(filename),
            path: ip + ':' + port + '/uploads/finished/' + path.basename(filename),
            type: mime.lookup(filename).substring(0, 5)
        };

    if (stats.isDirectory()) {
        info.type = "folder";
        info.children = fs.readdirSync(filename).map(function(child) {
            return dirTree(filename + '/' + child);
        });
    }
    return info;
}



http.createServer(function(request, response) {

    if(request.method.toLowerCase() == 'get') {
        var filePath = './content' + request.url;
        if (filePath == './content/') {
            filePath = './content/home.html';
        }
        if (filePath == './content/feed') {
            a = dirTree('./content/uploads/finished');
            response.end(JSON.stringify(a));
        }
        var extname = path.extname(filePath);
        var contentType = mime.lookup(extname);
        fs.exists(filePath, function (exists) {
            if (exists) {
                fs.readFile(filePath, function (error, content) {
                    if (error) {
                        response.writeHead(500);
                        response.end();
                    }
                    else {
                        response.writeHead(200, {'Content-Type': contentType});
                        response.end(content, 'utf-8');
                    }
                })
            } else {
                response.writeHead(404);
                response.end();
            }
        });
    }


    if (request.method.toLowerCase() == 'post') {
        var form = new formidable.IncomingForm;
        if (request.url == '/verify') {
            form.parse(request, function (err, fields, files) {
                for (i = 0; i < accounts.length; i++) {
                    if (fields.username == accounts[i].username && fields.password == accounts[i].password) {
                        fs.readFile('./content/uploadForm.html', function (error, content) {
                            if (error) {
                                response.end('There was an error');
                            } else {
                                response.end(content);
                            }
                        });
                    } else {
                        fs.readFile('./content/invalidLogin.html', function (error, content) {
                            if (error) {
                                response.end('There was an error');
                            } else {
                                response.end(content);
                            }
                        });
                    }
                }
            });
        } else if (request.url == '/upload') {
                var oldPath,
                newPath,
                fileName;

            form.uploadDir = './content/uploads/temp/';
            form.keepExtensions = true;
            form.parse(request, function (err, fields, files) {
                type = files['upload']['type'];
                fileName = files['upload']['name'];
                oldPath = files['upload']['path'];
                newPath = './content/uploads/finished/' + fileName;
            });

            form.on('end', function () {
                fs.rename(oldPath, newPath, function (err) {
                    if (err) {
                        response.end('There was an error with your request');
                        console.log('error')
                    } else {
                        response.end('<h1>Thanks for uploading ' + fileName + '<h1>');
                    }
                });
            });
        }
    }
}).listen(port);
console.log('listening on ' + port);

最佳答案

看起来您的脚本刚用完可用内存。

很可能您上传或下载了非常大的文件,并且您在接收或发送时读取了内存中的完整文件。

您应该改用流操作和逐 block 处理文件来重写代码。

关于javascript - Node.js 错误 "terminate called after throwing an instance of ' std::bad_alloc' what(): std::bad_alloc",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24419442/

相关文章:

javascript - 是否可以使构造函数属性分配列表变得更短?

javascript - 从 Angular Promise 访问 Form 元素和 div

c++ - VariantChangeType 和溢出

c++ - C++输入重定向在文件参数工作时导致错误

c++ - 编译期间未包含在目标中的 .h 文件会发生什么情况?

javascript - 为什么 XPiNC 中的任何 JS 对象总是未定义?

javascript - 匹配数字代码的正则表达式(数字、星号和锐号)

node.js - Firebase 函数(用 NodeJS 编写)在从实时数据库中删除对象时从云存储中删除文件

javascript - 如何使 npm 与我的自定义 npm 包一起使用?

node.js - 检查是否全局安装了特定的 NPM 包