SHARE
TWEET

Untitled

a guest Oct 22nd, 2019 59 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const net = require('net');
  2. const fs = require('fs');
  3.  
  4. const server = net.createServer((socket) => {
  5.     let buffer = "";
  6.     let parsedRequest = new Map();
  7.  
  8.     socket.on('data', function(data){
  9.         buffer += data;
  10.  
  11.         if(isDataEnd(buffer)){
  12.             parsedRequest = parseDataToMap(buffer);
  13.             console.log(parsedRequest);
  14.  
  15.             let requestLine = getRequestLine(buffer);
  16.             console.log(requestLine);
  17.         }
  18.     });
  19.  
  20.    
  21.     socket.on('error', (err) => {
  22.         // handle errors here
  23.         throw err;})
  24.  
  25. });
  26.  
  27.  
  28.  
  29. server.listen(process.env.PORT || 3000);
  30.  
  31. function isDataEnd(data) {
  32.     return data.endsWith('\r\n\r\n');
  33. }
  34.  
  35. function parseDataToMap(data) {
  36.     let dataMap = new Map();
  37.     data.split('\r\n').forEach((element, index) => {
  38.         if (index !== 0 && element !== '') {
  39.         let keyVal = element.split(':',2);
  40.         dataMap.set(keyVal[0], keyVal[1]);
  41.         }
  42.     });
  43.  
  44.     return dataMap;
  45. }
  46.  
  47. function getRequestLine(buffer) {
  48.     return buffer.toString().split(' ', 3)[1];;
  49. }
  50.  
  51. function responseFile (fileName, response) {
  52.     const filePath =  "/path/to/archive.rar" // or any file format
  53.  
  54.     fs.exists(filePath, function(exists){
  55.         if (exists) {
  56.             response.writeHead(200, {
  57.                 "Content-Type": "application/octet-stream",
  58.                 "Content-Disposition": "attachment; filename=" + fileName
  59.             });
  60.             fs.createReadStream(filePath).pipe(response);
  61.         } else {
  62.             response.writeHead(400, {"Content-Type": "text/plain"});
  63.             response.end("ERROR File does not exist");
  64.         }
  65.     });
  66. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Not a member of Pastebin yet?
Sign Up, it unlocks many cool features!
 
Top