0

我正在学习 node.js。在 cloud9 上尝试一些演示。演示很简单,只有2个js文件。我逐行检查,一切似乎都很好。请帮我调试它。

  1. 资源.js 文件。

            var util = require('util');
            var EventEmitter = require('events').EventEmitter;
    
            function Resource(m){
    
                var maxEvents = m;
                var self = this;
    
                process.nextTick(function(){
                    var count = 0;
    
                    self.emit('start');
                    var t = setInterval(function(){
                        self.emit('data', ++count);
    
                        if(count === maxEvents){
                            self.emit('end', count);
                            clearInterval(t);
                        }
                    }, 10);
                });
    
            };
    
            util.inherits(Resource, EventEmitter);
    
  2. 7-extEmitter.js

            var Resource = require('./resource');
    
    
            var r = new Resource(7);
    
    
            r.on('start', function(){
                console.log("I've started!");
            });
    
            r.on('data', function(d){
                console.log("    I received data -> " + d);
            });
    
            r.on('end', function(t){
                console.log("I'm done, with " + t + " data events.");
            });
    

这是我收到的错误消息:

            Your code is running at 'http://node.myw714.c9.io'.
            Important: use 'process.env.PORT' as the port and 'process.env.IP' as the host in your scripts!
            /var/lib/stickshift/511e07b5500446f25c0001bd/app-root/data/407149/7-extEmitter.js:4
            var r = new Resource(7);

              ^
            TypeError: object is not a function
                at Object. (/var/lib/stickshift/511e07b5500446f25c0001bd/app-root/data/407149/7-extEmitter.js:4:9)
                at Module._compile (module.js:449:26)
                at Object.Module._extensions..js (module.js:467:10)
                at Module.load (module.js:356:32)
                at Function.Module._load (module.js:312:12)
                at Module.runMain (module.js:492:10)
                at process.startup.processNextTick.process._tickCallback (node.js:244:9)
4

2 回答 2

0

您只需要删除该初始化代码。

    var r = require('./resource');


    r.on('start', function(){
        console.log("I've started!");
    });

    r.on('data', function(d){
        console.log("    I received data -> " + d);
    });

    r.on('end', function(t){
        console.log("I'm done, with " + t + " data events.");
    });

并在resource.js中添加这一行,如果你想让它更通用,你应该改变函数结构以允许设置值m。

module.exports = new Resource(7);
于 2013-02-17T00:33:23.240 回答
0

在 resource.js 文件中的 utils.inherit 下,您只需添加以下内容:

module.exports = Resource;  

其余的代码都很好。

于 2015-09-04T16:02:33.303 回答