好的,这个问题必须是一个非常简单的问题,但我刚开始学习节点。我也是javascript的新手,所以,请不要怜悯指出下面的错误指示。
特别是我有两个文件:
当我尝试打印出刚刚初始化的内容时,我会遇到两个奇怪的错误:
文件“slave.js”中的从属代码:
var http = require ("http");
function Slave () {
}
Slave.prototype.ID = undefined;
Slave.prototype.coordinator = false;
Slave.prototype.httpServer = undefined;
Slave.prototype.thePort = undefined;
Slave.prototype.isCoordinator = function () { return this.coordinator; }
/*****************************************************************/
function handle_incoming_request (req, res) {
console.log("INCOMING REQUEST: " + req.method + " " + req.url);
res.writeHead (200, { "Content-Type" : "application/json" });
res.end( JSON.stringify({ "error" : null }) + "\n" );
}
exports.createSlave = function (id, coordinatorK, port) {
var temp = new Slave ();
temp.ID = id;
temp.coordinator = coordinatorK;
temp.thePort = port;
temp.httpServer = http.createServer(handle_incoming_request);
temp.httpServer.listen (temp.thePort);
console.log ("Slave (" + (temp.isCoordinator() ? "coordinator" : "regular") + ") with ID " + temp.ID + " is listening to port " + temp.thePort);
console.log ("--------------------------------------------");
return temp;
}
现在,主文件。
var http = require ("http");
var url = require ("url");
var a = require ("./slave.js");
var i, temp;
var myArray = new Array ();
for (i = 0; i < 4; i++) {
var newID = i + 1;
var newPort = 8000 + i + 1;
var coordinatorIndicator = false;
if ((i % 4) == 0) {
coordinatorIndicator = true; // Say, this is going to be a coordinator
}
temp = a.createSlave (newID, coordinatorIndicator, newPort);
console.log ("New slave is : " + temp);
console.log ("Stringified is: " + JSON.stringify(temp));
myArray.push(temp);
}
答案 0 :(得分:3)
您正在尝试对http.createServer(...)
的结果进行字符串化。这不是你想要做的,所以当你创建那个属性时,通过使用Object.defineProperty()
来定义它是不可枚举的。
exports.createSlave = function (id, coordinatorK, port) {
var temp = new Slave ();
temp.ID = id;
temp.coordinator = coordinatorK;
temp.thePort = port;
Object.defineProperty(temp, "httpServer", {
value: http.createServer(handle_incoming_request),
enumerable: false, // this is actually the default, so you could remove it
configurable: true,
writeable: true
});
temp.httpServer.listen (temp.thePort);
return temp;
}
这样JSON.stringify
无法达到该属性,从而治愈了对象的枚举。
答案 1 :(得分:2)
问题是具有循环引用的httpServer
对象的属性temp
。您可以使用上一个答案中提到的Ecmascript5
属性定义将其设置为不可枚举,或者您可以使用JSON.stringify的replacer函数来自定义它,而不是对httpServer
属性进行字符串化。
console.log ("Stringified is: " + JSON.stringify(temp, function(key, value){
if(key === 'httpServer') return undefined;
return value;
}));