Node.js中的模块

时间:2014-02-09 23:46:16

标签: javascript node.js

我试图了解如何使用node.js中的模块来组织我的代码。这是我的两个文件1. server.js 2. index.js

server.js

var http = require("http");

function onRequest(request, response) {
    console.log("Request received.");
    response.writeHead(200, {"Content-Type": "text/plain"});
    response.write("Hello World");
    response.end();
}

exports.start = function () {
http.createServer(onRequest).listen(8888);
console.log("Server has started.");
}

index.js

var server = require('./server.js').inspect;

server.start();

但是当我执行

node index.js

我收到以下错误。

ashwin@ashwin-vm:~/winshare/node-tut1$ node index.js

/home/ashwin/winshare/node-tut1/index.js:3
server.start();
   ^
TypeError: Cannot call method 'start' of undefined
at Object.<anonymous> (/home/ashwin/winshare/node-tut1/index.js:3:8)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:902:3
ashwin@ashwin-vm:~/winshare/node-tut1$ 

以下是我的节点和Ubuntu版本

ashwin@ashwin-vm:~/winshare/node-tut1$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 13.10
Release:    13.10
Codename:   saucy
ashwin@ashwin-vm:~/winshare/node-tut1$ 
ashwin@ashwin-vm:~/winshare/node-tut1$ node --version
v0.10.25

1 个答案:

答案 0 :(得分:4)

从此行中删除.inspect

var server = require('./server.js').inspect;