Skip to content

Instantly share code, notes, and snippets.

@ifukazoo
Created June 15, 2014 14:13
Show Gist options
  • Select an option

  • Save ifukazoo/1167ecc32b2383f377cd to your computer and use it in GitHub Desktop.

Select an option

Save ifukazoo/1167ecc32b2383f377cd to your computer and use it in GitHub Desktop.
nodejs static
#!/usr/bin/env node
'use strict';
var http = require('http');
var url = require('url');
var fs = require('fs');
var mime = require('mime');
var exec = require('child_process').exec;
var db = {};
var port;
if (process.argv.length !== 3) {
console.log("usage:" + process[1] + " <port>");
process.exit(1);
}
port = process.argv[2];
var doGet = function(req, res) {
var pathName = url.parse(req.url)['pathname'];
if (pathName === '/') {
pathName += 'index.html';
}
pathName = '.' + pathName;
console.log(pathName);
fs.exists(pathName, function(exists) {
if (exists) {
doGetFile(pathName, res);
} else {
res.statusCode = 404;
res.writeHead(404, { 'Content-Length': 0, 'Connection': 'close'});
res.end();
}
});
};
var doGetFile = function(path, res) {
fs.readFile(path, function(e, content) {
if (e) {
res.writeHead(500, e.message,
{ 'Content-Length': 0, 'Connection': 'close'});
res.end();
} else {
res.writeHead(200, {
'Content-Length': content.length,
'Content-Type': mime.lookup(path),
'Connection': 'close'});
res.write(content);
res.end();
}
});
};
var doPost = function(req, res) {
var data = '';
req.on('data', function(chunk) {
data += chunk;
});
req.on('end', function() {
var api = url.parse(req.url)['pathname'];
console.log(api);
switch (api) {
case '/data':
try {
var json = JSON.parse(data);
console.log(json);
db[req.headers['user-agent']] = json;
} catch (e) {
res.writeHead(400, e.message,
{ 'Content-Length': 0, 'Connection': 'close'});
} finally {
res.end();
}
break;
case '/file':
console.log(data);
db['last_file'] = data;
res.end();
break;
default:
res.end();
break;
}
});
};
var server = http.createServer(function(req, res) {
if (req.method === 'GET') {
console.log('GET');
doGet(req, res);
} else if (req.method === 'POST') {
console.log('POST');
doPost(req, res);
}
});
server.on('clientError', function(e) {
console.log('Client Error: ', e.message);
});
server.on('error', function(e) {
console.log('Server Error: ', e.message);
});
exec('ifconfig |grep -1 "^eth0" |grep inet', function(err, stdout, stderr) {
var result = stdout.match(/(\d{1,3}\.){3}\d{1,3}/);
server.listen(port, function() {
console.log('ip = ' + result[0]);
console.log('port = ' + port);
console.log('listening ...');
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment