Skip to content

Instantly share code, notes, and snippets.

@fdecampredon
Last active November 25, 2015 21:58
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save fdecampredon/86ccbba3863bccaec7dd to your computer and use it in GitHub Desktop.
Save fdecampredon/86ccbba3863bccaec7dd to your computer and use it in GitHub Desktop.
Obtaining client window size on server
/*jshint node:true*/
var http = require('http');
var fs = require('fs');
var url = require('url');
var querystring = require('querystring');
var head = fs.readFileSync('head.html','UTF-8');
//<head>
// <meta charset="utf-8">
//
// <script type="text/javascript">
// (function () {
// var src = '/layoutInfo?reqId='+ {{requestId}} +
// '&width=' + document.documentElement.clientWidth +
// '&height=' + document.documentElement.clientHeight;
//
// document.write('<script type="text/javascript" src="'+src+'" ></'+'script>')
// })()
// </script>
//</head>
var uidHelper = 0;
var pendingReq = {};
function resolveReqId(id, layoutInfo) {
if (pendingReq[id]) {
pendingReq[id](null, layoutInfo);
delete pendingReq[id];
}
}
function waitReqId(id, callback) {
pendingReq[id] = callback;
}
http.createServer(function (req, res) {
console.log(req.url);
if (req.url === '/') {
res.writeHead(200, {'Content-Type': 'text/html'});
var reqId = (uidHelper++);
res.write(head.replace(/{{requestId}}/g, reqId));
waitReqId(reqId, function (err, layouInfo) {
res.write('<body>');
res.write('<pre>' + JSON.stringify(layouInfo) + '</pre>');
res.end('</body>');
});
} else if (req.url.indexOf('/layoutInfo' === 0)) {
var info = url.parse(req.url);
if (info && info.query ) {
var query = querystring.parse(info.query);
resolveReqId(query.reqId, {width: query.width, height: query.height});
}
res.writeHead(200, {'Content-Type': 'application/json'});
res.end('');
}
}).listen(3000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment