node.js 实战上的例子为什么无法运行?
发布于 10 年前 作者 egrcc 4111 次浏览 最后一次编辑是 8 年前 来自 问答

初学者,在看 nodejs in action ,第三章运行了两个例子都没有成功。一个是pubsub.js,源码如下: var events = require(‘events’) , net = require(‘net’);

var channel = new events.EventEmitter();
channel.clients = {};
channel.subscriptions = {};

channel.on('join', function(id, client) {
  this.clients[id] = client; 
  this.subscriptions[id] = function(senderId, message) {
    if (id != senderId) { 
      this.clients[id].write(message);
    }
  }
  this.on('broadcast', this.subscriptions[id]); 
});

channel.on('leave', function(id) { 
  channel.removeListener('broadcast', this.subscriptions[id]); 
  channel.emit('broadcast', id, id + " has left the chat.\n");
});

channel.on('shutdown', function() {
  channel.emit('broadcast', '', "Chat has shut down.\n");
  channel.removeAllListeners('broadcast');
});

var server = net.createServer(function (client) {
  var id = client.remoteAddress + ':' + client.remotePort;
  client.on('connect', function() {
    channel.emit('join', id, client); 
  });
  client.on('data', function(data) {
    data = data.toString();
    if (data == "shutdown\r\n") {
      channel.emit('shutdown');
    }
    channel.emit('broadcast', id, data); 
  });
  client.on('close', function() {
    channel.emit('leave', id); 
  });
});
server.listen(8888);

运行 node pubsub.js后,又新开了两个终端,分别运行 telnet 127.0.0.1 8888,在一个终端中输入消息,并没有在另一个终端中出现。 另一个例子是event_emitter_extend.js,源码如下: function Watcher(watchDir, processedDir) { this.watchDir = watchDir; this.processedDir = processedDir; }

var events = require('events')
  , util = require('util');

util.inherits(Watcher, events.EventEmitter);

var fs = require('fs')
  , watchDir = './watch'
  , processedDir  = './done';

Watcher.prototype.watch = function() { 
  var watcher = this;
  fs.readdir(this.watchDir, function(err, files) {
    if (err) throw err;
    for(index in files) {
      watcher.emit('process', files[index]); 
    }
  })
}

Watcher.prototype.start = function() { 
  var watcher = this;
  fs.watchFile(watchDir, function() {
    watcher.watch();
  });
}

var watcher = new Watcher(watchDir, processedDir);

watcher.on('process', function process(file) {
  var watchFile      = this.watchDir + '/' + file;
  var processedFile  = this.processedDir + '/' + file.toLowerCase();

  fs.rename(watchFile, processedFile, function(err) {
    if (err) throw err;
  });
});

watcher.start();

运行 node event_emitter_extend.js 后也没有把watch中的文件重命名到done文件夹。 问题可能比较傻逼,我知道是不是我那里出错了?

回到顶部