GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — fullstack-javascript/08-test/mb-server.js at master · fkanout/fullstack-javascript Expand file tree/ Copy pathmb-server.jsMore file actions 67 lines (62 loc) · 2.31 KB / Copy pathmb-server.jsFile metadata and controls67 lines (62 loc) · 2.31 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 var http = require('http') // Loads http module var util= require('util') // Usefull functions var querystring = require('querystring') // Loads querystring module, we'll need it to serialize and deserialize objects and query strings var port = process.env.PORT || 1337 var messages = [] // This array will hold our messages messages.push({ 'name': 'John', 'message': 'hi' }) // Sample message to test list method exports.server = http.createServer(function (req, res) { // Creates server if (req.method == 'POST' && req.url == '/messages/create.json') { // If method is POST and URL is messages/ add message to the array var message = '' req.on('data', function(data, msg){ console.log(data.toString('utf-8')) message = exports.addMessage(data.toString('utf-8')) // Data is type of Buffer and must be converted to string with encoding UTF-8 first // Adds message to the array }) req.on('end', function(){ console.log('message', util.inspect(message, true, null)) console.log('messages:', util.inspect(messages, true, null)) // Debugging output into the terminal res.writeHead(200, {'Content-Type': 'text/plain'}) // Sets the right header and status code res.end(message) // Out put message, should add object id }) } else if (req.method == 'GET' && req.url == '/messages/list.json') { // If method is GET and URL is /messages output list of messages var body = exports.getMessages() // Body will hold our output res.writeHead(200, { 'Content-Length': body.length, 'Content-Type': 'text/plain' }) res.end(body) } else { res.writeHead(200, {'Content-Type': 'text/plain'}) // Sets the right header and status code res.end('Supported endpoints: \n/messages/list.json\n/messages/create.json') // Outputs string with line end symbol } }).listen(port) // Sets port and IP address of the server console.log('Server running at http://127.0.0.1:%s/', port) exports.getMessages = function() { return JSON.stringify(messages) // Output array of messages as a string/text } exports.addMessage = function (data){ messages.push(querystring.parse(data)) // To convert string into JavaScript object we use parse/deserializer return JSON.stringify(querystring.parse(data)) // Output new message in JSON as a string } |
| You are visitor 01402792 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |