好吧,这肯定是一个非常简单的问题,但我刚刚开始学习 Node 。我也是 javascript 新手,所以,请毫不留情地指出下面的错误方向。
特别是我有两个文件:
- 一个类有一个在不同端口创建一些从属服务器的类
- 另一个是生成从站的“主”文件
当我尝试打印出刚刚初始化的内容时,出现两个奇怪的错误:
- connections 属性已弃用。使用 getConnections() 方法,然后
- 当我尝试在新对象中应用 JSON.stringify 时,它崩溃了(将循环结构转换为 JSON)
文件“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);
}
最佳答案
您正在尝试对 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
将无法访问该属性来固化其对象的枚举。
关于javascript - JSON.stringify 在新创建的对象( Node 、javascript)上失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18726056/