我有以下代码:
var io = require('socket.io-client');
function connect_to_room(callback){
console.log(typeof io.connect);
var socket = io.connect('http://website.com/socket/');
socket.on('connect', function(){
console.log("connected");
socket.on('event', function(data){
console.log("event happened");
console.log(data);
});
socket.on('disconnect', function(){
console.log("disconnected");
});
});
}
exports.connect = connect_to_room();
当我调用connect_to_room()
时,它会在控制台中记录“function”,然后抛出这个错误:
TypeError: Property 'connect' of object #<Object> is not a function
at Request._callback (C:\Users\randomuser\Downloads\somecode\somecode\dev\init.js:151:35)
at Request.self.callback (C:\Users\randomuser\Downloads\somecode\somecode\dev\node_modules\request\request.js:121:22)
at Request.EventEmitter.emit (events.js:98:17)
at Request.<anonymous> (C:\Users\randomuser\Downloads\somecode\somecode\dev\node_modules\request\request.js:978:14)
at Request.EventEmitter.emit (events.js:117:20)
at IncomingMessage.<anonymous> (C:\Users\randomuser\Downloads\somecode\somecode\dev\node_modules\request\request.js:92
9:12)
at IncomingMessage.EventEmitter.emit (events.js:117:20)
at _stream_readable.js:920:16
at process._tickCallback (node.js:415:13)
我在这里做错了什么?
node --version
返回v0.10.26
package.json有依赖关系(已全部安装):
"dependencies" : {
"jsonfile" : "1.1.1",
"log4js" : "0.6.12",
"mkdirp" : "0.3.5",
"npm" : "1.4.4",
"request" : "2.34.0",
"jsdom" : "0.10.2",
"socket.io-client" : "0.9.16"
},
答案 0 :(得分:1)
你有一个错字
var sock
应该是
var socket
另一个问题:
exports.connect = connect_to_room();
应该是
exports.connect = connect_to_room;
答案 1 :(得分:0)
试试这个:
var socket = require('socket.io-client')('http://website.com/socket/');
function connect_to_room(callback){
console.log(typeof io.connect);
socket.on('connect', function(){
console.log("connected");
socket.on('event', function(data){
console.log("event happened");
console.log(data);
});
socket.on('disconnect', function(){
console.log("disconnected");
});
});
}
exports.connect = connect_to_room(function(back){ });