Created
          December 23, 2018 19:11 
        
      - 
      
- 
        Save bertiespell/4e252cd1cc4f12fd32cf50eada13459a to your computer and use it in GitHub Desktop. 
    A simple server that saves key/value pairs
  
        
  
    
      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
    
  
  
    
  | var http = require('http'); | |
| const storedValues = {}; | |
| http.createServer((request, response) => { | |
| // check path is supported | |
| const path = request.url.split('?'); | |
| if (!path || path.length !== 2) { | |
| response.writeHead(404); | |
| response.end(); | |
| return; | |
| } | |
| // check we have a valid key/value pair | |
| const keyValuePair = path[1].split('='); | |
| if (!keyValuePair || keyValuePair.length !== 2) { | |
| response.writeHead(400); | |
| response.end(); | |
| return; | |
| } | |
| if (path[0] === '/set') { | |
| storedValues[keyValuePair[0]] = keyValuePair[1]; | |
| response.writeHead(200); | |
| response.end(keyValuePair[1]); | |
| return; | |
| } | |
| else if (path[0] === '/get') { | |
| const returnValue = storedValues[keyValuePair[1]]; | |
| if (returnValue === undefined) { | |
| response.writeHead(404); | |
| response.end('key not set'); | |
| } else { | |
| response.writeHead(200); | |
| response.end(storedValues[keyValuePair[1]]); | |
| } | |
| return; | |
| } else { // unsupported path | |
| response.writeHead(404); | |
| response.end(); | |
| return; | |
| } | |
| }).listen(4000); | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment