节点JS中的内存错误(node :: smalloc :: Alloc)

时间:2015-08-06 13:14:15

标签: javascript node.js fatal-error alloc

我是节点Js的新手,我已经构建了一个非常简单的服务器,它向我发送了一个我要求的zip文件。这一切都正常,但在一些请求发生崩溃后,我在终端上可视化了这条消息:

致命错误:node :: smalloc :: Alloc(v8 :: Handle,size_t,v8 :: ExternalArrayType)Out of Memory

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

var port = 1337;


// create http server
var server = http.createServer(function (request, response) {

	var path = require('url').parse(request.url, true);
	console.log('requested ' + path.pathname);

	//get zipped resoures
	if (path.pathname == '/getzip') {
		console.log(request.url);
		var queryData = url.parse(request.url, true).query;
		if (queryData.name) {
			var filename = queryData.name;
			//open corrisponding file
			var zipFile = fs.readFileSync('packets/' + filename);
			response.writeHead(200, {
	   	    	'Content-Type': 'application/x-zip',
	   	    	'Content-disposition': 'attachment; filename=data.zip'
	  		});
	  		//send file in response
			response.end(zipFile);
		}
		else {
			response.writeHead(200, {'Content-Type': 'text/plain'});
	 		response.end('{error = "bad url"}');
		}
	}

}).listen(port);
server.timeout = 1000000;

你知道它可能是什么吗?这段代码看起来很简单。

1 个答案:

答案 0 :(得分:2)

不应将整个文件读入内存,而应该使用streams

response.writeHead(200, {
  'Content-Type'        : 'application/x-zip',
  'Content-disposition' : 'attachment; filename=data.zip'
});
fs.createReadStream('packets/' + filename).pipe(response);