1

我正在玩 nodejs 并专门研究 nowjs

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

 //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">

控制台立即返回“现在”未定义

4

1 回答 1

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(来自文档

在服务器上

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>
于 2012-07-11T10:56:08.757 回答