“学习节点JS”示例 - '超级构造函数“继承”必须不'+'

时间:2017-07-31 22:24:37

标签: node.js

我正在寻找O'Reilly“学习节点JS”一书中的练习,我遇到了一个不可挽回的例子。我的代码如下:

"use strict";

var util = require('util');
var eventEmitter = require('events').eventEmitter;
var fs = require('fs')

function InputChecker(name, file) {
    this.name = name;
    this.writeStream = fs.createWriteStream('./' + file + '.txt',
        {'flags': 'a',
         'encoding': 'utf8', 
         'mode' : 0o666});
};

util.inherits(InputChecker, eventEmitter);

InputChecker.prototype.check = function check(input) {
    let command = input.trim().substr(0,3);
    if (command == 'wr') {
        this.emit('write', input.substr(3, input.length));
    } else if (command == 'en:') {
        this.emit('end');
    } else {
        this.emit('echo', input);
    }
};

let ic = new InputChecker('Shelley', 'output');

ic.on('write', function(data) {
    this.writeStream.write(data, 'utf8');
});

ic.on('echo', function(data) {
    process.stdout.write(ict.name + ' wrote ' + data);
});

ic.on('end', function() {
    process.exit();
});

process.stdin.setEncoding('utf8');
process.stdin.on('readable', function() {
    let input = process.stdin.read();
    if (input != null)
        ic.check(input);
});

错误是:

[user@MacBook-Pro NodeJS]$ node fileevent.js   
util.js:957
throw new TypeError('The super constructor to "inherits" must not ' +
^

TypeError: The super constructor to "inherits" must not be null or undefined
at Object.exports.inherits (util.js:957:11)
at Object.<anonymous> (/Users/user/Documents/NodeJS/fileevent.js:15:6)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.runMain (module.js:604:10)
at run (bootstrap_node.js:389:7)
at startup (bootstrap_node.js:149:9)`

任何帮助表示赞赏! TIA!

1 个答案:

答案 0 :(得分:2)

你的错误从这里开始:

var eventEmitter = require('events').eventEmitter;

EventEmitter对象是title-case,因为它是一个类名。将其重写为:

在语义上是正确的
var EventEmitter = require('events').EventEmitter;

但是,这是在节点v0.10x及更早版本中获取EventEmitter类的旧方法,仅支持向后兼容性。现代化的方法是:

const EventEmitter = require('events');

并将其余引用从eventEmitter重构为EventEmitter,以遵循通常使用大写字母命名类的nodejs约定。