我有一个book.js
和server.js
文件。我运行node ./server.js
,服务器开始运行。我打开谷歌浏览器并打开开发者控制台,并输入book.rate(10),我的发射不会发生在任何地方。也许我不理解eventemitters。错误是“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;
答案 0 :(得分:1)
您获得book is not defined
,因为您尚未在客户端定义book
,您只在服务器端定义了它。
如果没有某种额外的库/代码来提供这种功能,你无法从浏览器中神奇地访问服务器端变量。