好的,这一定是一个非常简单的问题,但我刚刚开始学习节点。我也是 javascript 的新手,所以,请毫不留情地指出下面的错误方向。
特别是我有两个文件:
- 一个类可以在不同的端口创建一些从服务器
- 另一个是生成从属的“主”文件
当我试图打印出我刚刚初始化的内容时,我得到了两个奇怪的错误:
- 不推荐使用连接属性。使用 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);
}