Forked from fdecampredon/gist:86ccbba3863bccaec7dd
Created
November 25, 2015 21:58
-
-
Save pthrasher/f2a03810fe9bce77888d to your computer and use it in GitHub Desktop.
Obtaining client window size on server
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*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