如何使用node.js在服务器和客户端之间共享通用功能

时间:2014-01-22 12:59:32

标签: node.js prototype require

以下是我的申请结构

enter image description here

prototype.js 文件中,我有以下代码:

(function(exports) {
    exports.foo = function() {
        return 'bar';
    };
})((typeof process === 'undefined' || !process.versions) ? window.common = window.common || {} : exports);

app.js包含

var express = require('express'),app = express(),server = require('http').createServer(app),io = require('socket.io').listen(server),port = 3000,path = require('path');
var common = require('common/prototype');
console.log(common.foo());
// listening to port...
server.listen(port);
//Object to save clients data
var users = [];
app.use(express.static(path.join(__dirname, 'public')));

app.get('/', function (req, res) {
    res.sendfile('/public/index.html');
});

index.html 包含

<!doctype html>
<html lang="en">
<head>
    <title>Socket.io Demo</title>   
</head>
<body>    
    <script src="/socket.io/socket.io.js"></script>
    <script src="/common/prototype.js"></script>  
    <script>
    alert(window.common.foo()); //This line will gives me an error TypeError: window.common is undefined
    </script>
</body>
</html>

现在我想打印 您好,我也是服务器和客户端

现在我可以使用以下行从服务器端打印

var common = require('common/prototype');
console.log(common.foo());

但无法在客户端显示提醒。你能不能帮我找到问题的根本原因。

1 个答案:

答案 0 :(得分:0)

根本原因是,当您在HTML中执行<script src="/common/prototype.js"></script>时,将无法获取文件,因为Express静态中间件仅查找公用文件夹下的文件。

快速测试方法是将prototype.js复制到javascript内的public文件夹。然后更新脚本标记以引用该文件,如下所示<script src="/javascripts/prototype.js"></script>

要记住的是,node_modules下的JavaScript文件不会自动提供给浏览器。