Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nodejs - how to make functions happen just once?

Tags:

node.js

I got a simple chat app utilizing socket.io and express framework, below is part of the code:

var app = express.createServer();
var socket = io.listen(app);

var store = new express.session.MemoryStore;
app.use(express.cookieParser());
app.use(express.session({ 
    secret: 'something', 
    store: store, 
    cookie: { 
        maxAge: 60*60*24*30*1000
    }
}));

app.get('/', function(req, res){
    socket.on('connection', function(client) {
        req.session.ioid = client.sessionId;
        req.session.channel = req.param('channel');
        req.session.username = req.param('username');
        //I want the code below happen just once                
        res.header('Content-Type', 'text/plain');
        res.header('Access-Control-Allow-Origin', '*');
        res.send({sid:req.session.id});
    });
});

You can see the res.header and res.send in the socket.on closure. Those "res" will execute constantly, and cause error "Can't set headers after they are sent."

I'm looking for a way to make the block-

res.header('Content-Type', 'text/plain');

res.header('Access-Control-Allow-Origin', '*');

res.send({sid:req.session.id});

-happen just once.

like image 276
angry kiwi Avatar asked Dec 21 '22 13:12

angry kiwi


1 Answers

app.get('/', function(req, res){
    socket.on("connection", function(client) {
        req.session.ioid = client.sessionId;
        req.session.channel = req.param('channel');
        req.session.username = req.param('username');
    });

    socket.once('connection', function(client) {
        //I want the code below happen just once                
        res.header('Content-Type', 'text/plain');
        res.header('Access-Control-Allow-Origin', '*');
        res.send({sid:req.session.id});
    });
});

Use .once

like image 130
Raynos Avatar answered Dec 24 '22 03:12

Raynos