从路径中分离逻辑

时间:2015-07-24 08:26:04

标签: node.js model-view-controller express socket.io

我对Node非常陌生,我使用快递。 我试图实现简单的文件浏览器。 在这里谈论了一些代码:

(root dir是/ app for this ex。)

我的app.js:

var express = require('express');
var fs = require('fs');
var path = require('path');
var ejs = require('ejs');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);

var explorer = require('./routes/explorer');

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use("/public", express.static(__dirname + '/public'));
app.use('/', explorer);


server.listen(3000,function(){
    console.log('Server started on http://localhost:3000');
});

io.on('connection',function(client){
    console.log('connection with io established');
});

module.exports.app = app;
module.exports.server = server;

看到我有路由' /'探险家

和explorer.js:

var express = require('express');
var router = express.Router();
var fs = require('fs');

router.get('/', function(req, res, next) {
  res.render('explorer',{
    currentPath : currentPath
  });
});

function getUserHome() {
      var rawPath =  process.env[(process.platform == 'win32') ? 'USERPROFILE' : 'HOME'];
      return rawPath;
}

function clicked(){
    console.log(getUserHome());
}

view explorer.ejs:

<div class="clickable">clickme</div>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost:3000');
$('.clickable').click(function(){
    socket.emit('clicked');
});
</script>

基本上我想抓住&#34;点击&#34;从视图中发出并触发explorer.js中单击的函数。换句话说,我希望视图和explorer.js通过socket.io进行通信,因此视图可以与文件系统进行通信。 我尝试了一些方法并且犯了一堆错误。

非常感谢你!

1 个答案:

答案 0 :(得分:0)

所以你已经触发了这个事件并点击了#39;在您的客户端:

// Client side :
var socket = io.connect('http://localhost:3000');
$('.clickable').click(function(){
    socket.emit('clicked');
});

现在,您必须在explorer.js文件中的服务器端捕获它:

// Server side :
// Instanciate your socket.io on the server side
var io =  require('socket.io')(server)

// Listen for a client connection :
io.sockets.on('connection', function(socket){
    // Inside the connection, you can now declare each function for each event triggered on the client side

    socket.on('clicked', function() {
        //  This is your callback,
        //+ the code in this scope will be executed
        //+ only when the event 'clicked' is emitted
        cliked();
    });
});