NowJs服务器与Web服务器不同

时间:2012-07-11 10:49:00

标签: node.js nowjs-sockets

我正在玩nodejs,特别是看看nowjs

我现在已经运行在运行节点的服务器上并且我有一个单独的Web服务器。我成功地让节点服务器返回客户端脚本,并在Web服务器上引用它。这将返回200响应代码并且看起来都很好。但是我收到javascript错误告诉我“现在”未定义。据我所知,'now'变量应该可以通过客户端脚本获得,但似乎并非如此。有谁知道这个设置是否可行?所以设置类似于下面的伪代码

 //Server 1 node.com
 if(request.url === '/nowjs/now.js'){
      var file = 'path_to_clientlib/now.js';
  fs.readFile(file, function(e, data) {

        if (e) {
           throw e;
        }

         response.writeHead(200,{'Content-Type': 'application/javascript'});
          response.end(data);
}

和server.com

   <script src="/jquery.js"></script>
   <script src="http://node.com/nowjs/now.js"></script> <!-- This is returned properly -->
   <script>
   $(document).ready(function(){

    now.receiveMessage = function(name, message){
      $("#messages").append("<br>" + name + ": " + message);
    }

   $("#send-button").click(function(){
     now.distributeMessage($("#text-input").val());
     $("#text-input").val("");
   });

   now.name = prompt("What's your name?", "");

   });
   </script>

  <div id="messages"></div>
  <input type="text" id="text-input">
  <input type="button" value="Send" id="send-button">

直接退出控制台只是返回'now'未定义

1 个答案:

答案 0 :(得分:0)

首先,有足够的模块提供静态文件服务支持,但如果你想手动提供文件,我会这样做......

var mime = require('mime')   // Get mime type based on file extension. use "npm install mime"
  , util = require('util')
  , fs = require('fs');

function serveFile(filename, res) {
  var filePath = process.cwd() + filename;
  var stat = fs.statSync(filePath);

  res.writeHead(200, {
     'Content-Type':mime.lookup(filePath),
     'Content-Length':stat.size
  });

  var readStream = fs.createReadStream(filePath);

  return util.pump(readStream, res);
}

// Your code...

或者查看NPMGithub上的 node-static 模块

关于如何使用NowJS(from the docs

在服务器上

var httpServer = require('http').createServer(function(req, response){ 

  // See code above how to serve static files...

});

httpServer.listen(8080);

var nowjs = require("now");
var everyone = nowjs.initialize(httpServer);

everyone.now.logStuff = function(msg){
  console.log(msg);
}

在客户端

<script type="text/javascript" src="http://localhost:8080/nowjs/now.js"></script>

<script type="text/javascript">
  now.ready(function(){
    // "Hello World!" will print on server
    now.logStuff("Hello World!");
  });
</script>