Showing posts with label http. Show all posts
Showing posts with label http. Show all posts

Monday 15 July 2019

Http echo service written in Node.js

I have added a small repo on Github that shows how to create a simple HTTP echo service. https://github.com/toreaurstadboss/NodeJsHttpEchoServer The server.js is script is this:
let http = require('http');

console.log('Attempting to start the Node.js echos server on port 8081..')
http.createServer().on('request', function(request, response){
 request.pipe(response);
}).on('close', function(){
    console.log('The Node.js echo server has been closed.')
})
.listen(8081);

console.log('Node.js echo server started on port 8081.')

This will pipe out the requesting data to the response. Test it out with this command for example in a command window: curl -d "Hello dog" http://localhost:8081 Note - use not Powershell for this command as Powershell has aliased curl command for Invoke-WebRequest. Rather install curl with Chocolatey for example, choco install curl

Friday 28 December 2018

Debugging http Node.js server requests and responses from shell

Here is a cool tip to inspect Node.js running an http process / server. First off, we start a simple http server in Node.js like this:

const http = require('http');

const server = http.createServer((req, res) => {
    res.end("

Why hello world!

\n"); }); server.listen(4242, () => { console.log("Server is running..."); });
This sets up a http server in Node.js. The http module is built-in in Node.js, we only have to require it (import in ES6). Now, just enter the following (I use Windows Subsystem for Linux - WSL in this case) in your shell to export NODE_DEBUG environment variable: export NODE_DEBUG=http We can now see requests and responses in our Node.js server! (Image below uses Wsl-Terminal as our terminal against WSL).