使node.js代码在浏览器中工作

时间:2015-01-25 11:18:12

标签: javascript node.js websocket

我是Node.js的新手,正在创建一个普通的聊天应用程序来了解它。我正在使用ws库

在我的实验中,我发现node.js代码并不直接在浏览器中工作(我更具体地说是require())。因此,为了使它在浏览器中工作,我不得不使用browserify将代码转换为浏览器兼容。

但转换后的代码会抛出未定义函数的错误

我的node.js代码

var WebSocket = require('ws')
  , ws = new WebSocket('ws://localhost:8080');
ws.on('open', function() {
    var firstMessage = '{"type":"name","message":"god"}';
    ws.send(firstMessage.toString());
});
ws.on('message', function(message) {
    console.log('received: %s', message);
});

我使用browserify转换代码

(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){

/**
 * Module dependencies.
 */

var global = (function() { return this; })();

/**
 * WebSocket constructor.
 */

var WebSocket = global.WebSocket || global.MozWebSocket;

/**
 * Module exports.
 */

module.exports = WebSocket ? ws : null;

    /**
     * WebSocket constructor.
     *
     * The third `opts` options object gets ignored in web browsers, since it's
     * non-standard, and throws a TypeError if passed to the constructor.
     * See: https://github.com/einaros/ws/issues/227
     *
     * @param {String} uri
     * @param {Array} protocols (optional)
     * @param {Object) opts (optional)
     * @api public
     */

    function ws(uri, protocols, opts) {
      var instance;
      if (protocols) {
        instance = new WebSocket(uri, protocols);
      } else {
        instance = new WebSocket(uri);
      }
      return instance;
    }

    if (WebSocket) ws.prototype = WebSocket.prototype;

    },{}],2:[function(require,module,exports){
    var WebSocket = require('ws')
      , ws = new WebSocket('ws://localhost:8080');
      console.log(ws);
    ws.on('open', function() {   //line that contains error
        var firstMessage = '{"type":"name","message":"Ayush"}';
        ws.send(firstMessage.toString());
    });
    ws.on('message', function(message) {
        console.log('received: %s', message);
    });
    },{"ws":1}]},{},[2]);

我的服务器代码

var WebSocketServer = require('ws').Server
  , wss = new WebSocketServer({port: 8080});

var index = 0;
var map = {};
wss.on('connection', function(ws) {
    map[index] = ws;
    var myindex = index;
    var username;
    index++;
    ws.on('message', function(message) {
        var json = JSON.parse(message);
        if(json.type == "name"){
            username = json.message;
            console.log(username);
        } else {
            //Print Message
        }
    });
    ws.send('something');

    ws.on('close', function(){
        console.log("Deleting index" + myindex);
        delete map[myindex];
    });
});

但是,当我使用browserify并使用我转换的代码时,它会在第50行引发错误。

未捕获的TypeError:undefined不是函数

1 个答案:

答案 0 :(得分:0)

ws库建立在原始TCP套接字之上。出于安全原因,您无法在客户端JavaScript中使用这些,因此这不起作用。您需要在浏览器中使用WebSocket构造函数。

成功浏览的唯一node.js库是那些不使用node.js标准库的文件库 - 文件系统,网络等。即,underscore等实用程序库和async