节点 EventEmitter 没有给出预期的结果

Node EventEmitter Not Giving Anticipated Results

我有一个 book.jsserver.js 文件。我运行 node ./server.js 并且服务器开始运行。我打开 Google Chrome 并打开开发人员控制台,然后输入 book.rate(10),但我的发射不会在任何地方发生。也许我不了解事件发射器。错误是“Uncaught Reference error: book is not defined

Server.js

var http = require('http');
var BookClass = require('./book.js');

http.createServer(function (req, res) {
   res.writeHead(200, {'Content-Type': 'text/plain'});
   res.end('Hello World\n');
var book = new BookClass();
book.on('rated', function() {
 console.log('rated '  + book.getPoints());
}); 
}).listen(9000, '127.0.0.1');
console.log('Server running at http://127.0.0.1:9000/');

Book.js

var util = require("util");
var events = require("events");
var Class = function() { };
util.inherits(Class, events.EventEmitter);
Class.prototype.ratePoints = 0;
Class.prototype.rate = function(points) {
   ratePoints = points;
   this.emit('rated');
};
Class.prototype.getPoints = function() {
   return ratePoints;
}
module.exports = Class;

你得到book is not defined是因为你没有在客户端定义book,你只在服务器端定义了它。

如果没有某种额外的 library/code 来提供那种功能,您就无法像从浏览器那样神奇地访问服务器端变量。