baniol
5/9/2014 - 1:33 PM

download file and log request with log4js, nodejs, http

download file and log request with log4js, nodejs, http

http  = require('http'),
url  = require('url'),
path  = require('path'),
log4js = require('log4js');

log4js.configure('./cfg_log4js.json');
var logger = log4js.getLogger('simplelog');

var server = http.createServer(function (req, res) {

  var file = __dirname + '/data.json';
  var filename = path.basename(file);

  var query = url.parse(req.url, true).query;

  logger.debug('username: ' + query.user + ', IP: ' + req.connection.remoteAddress);

  fs.readFile(path.join('data.json'), 'utf8', function (err, data) {
    res.setHeader('Content-disposition', 'attachment; filename=' + filename);
    res.setHeader('Content-type', 'application/json');
    res.write(data);
    res.end();
  });
});

server.listen(8080);
{
  "name": "download_file",
  "version": "0.0.1",
  "description": "Example how to download file and log request.",
  "dependencies": {
    "log4js": "^0.6.14"
  }
}
{
  "first_name": "your name",
  "surname": "your surname",
  "ip": "your IP"
}
{
  "appenders": [
    {
      "type": "file",
      "filename": "serverLog.log" ,
      "category": "simplelog",
      "backups" : 2,
      "maxLogSize": 20480,
      "description": "Example log."
    }]
}