undefined不是server.listen的函数

时间:2016-05-06 13:59:58

标签: node.js

我正在尝试将nodejs模块定义如下:

"use strict";
const
    fs = require('fs'),
    util = require('util'),
    net = require('net'),
    // server constructor
    NetWatcherServer = function(handler) {
        net.createServer(handler);
    };

// expose module methods
exports.NetWatcherServer = NetWatcherServer;
exports.createServer = function(handler){
    let server = new NetWatcherServer(handler);
    server.listen(5432, function() {
        console.log('Listening for subscribers...');
    });
    // should i be doing anything like:
    // util.inherits(server, ?????);
    // to simulate inheritance? what should be the ?????
    return server;
};

然而,当我尝试用它来调用它时:

"use strict";
const netWatcher = require('./net-watcher-server.js');
netWatcher.createServer(function(connection) {
    console.log('test');
});

然后我得到:

server.listen(5432, function() {
           ^
TypeError: undefined is not a function

我知道这意味着它无法识别listen上的函数server我确实看到nodejs提供了一个实用程序来提供原型(模拟继承)但我不是确定我应该如何使用exports.createServer我认为我应该添加类似的内容:

util.inherits(server, ?????);

但即使这是正确的,我也不知道该代替?????

2 个答案:

答案 0 :(得分:1)

new NetWatcherServer(handler);创建NetWatcherServer函数的新实例。您不需要此实例,只需要它生成的服务器。

只需调用函数:

let server = NetWatcherServer(handler);

并确保该函数返回一个值:

NetWatcherServer = function(handler) {
    return net.createServer(handler);
};

答案 1 :(得分:0)

您不从函数返回服务器实例。简单修复:

<html>
{% extends 'base.html' %}
<head>
    <title>{{title}}</title>
</head>
<body>
{% load crispy_forms_tags %}
{% load crispy_forms_field %}
{# image_thumbnail.html #}
{% load i18n %}
{% block jumbotron %}
    <div class="jumbotron">
      <h1>Edit your profile here</h1>
        <form method="Post" action="" enctype='multipart/form-data'>{%csrf_token%}
            {{ form2|crispy }}
            <input type="submit" name = "PictureForm" value = "Save Picture"></input>
        </form>

        <form method="Post" action="" enctype='multipart/form-data'>{%csrf_token%}
            {{ form1|crispy }}
            <input type="submit" name = "ProfileForm" value = "Save Information"></input>
        </form>

    </div>
{% endblock %}
</body>
</html>