Skip to content

1. NodeJS

Node.js has revolutionized server-side development, empowering developers to build scalable, high-performance web applications with JavaScript – the language of the web. In this wiki, you’ll find a wealth of resources covering a wide range of topics, from the basics of asynchronous programming and event-driven architecture to advanced techniques like building RESTful APIs, microservices, and real-time applications.

1. What is Node.js?

  • A runtime environment to execute JavaScript outside the browser.
  • Built on Chrome’s V8 JavaScript engine.
  • Uses event-driven, non-blocking I/O.

Use Cases

  • Web servers
  • RESTful APIs
  • Real-time applications (e.g., chat)

3. πŸ“ Setting Up Node.js

Installation

  • Install from nodejs.org
  • Verify with:
    Terminal window
    node -v
    npm -v

Initialize a Project

Terminal window
npm init

3. πŸ“¦ Creating a Basic HTTP Server

const http = require('http');
const server = http.createServer((req, res) => {
res.write('Hello from Node.js server!');
res.end();
});
server.listen(3000);

4. βœ… Handle Basic Get and Post

You can handle simple GET and POST requests using just Node.js and the http module β€” no Express needed.

4.1 Basic GET and POST Handling

const http = require('http');
const server = http.createServer((req, res) => {
const { method, url } = req;
// Set content type
res.setHeader('Content-Type', 'application/json');
if (method === 'GET' && url === '/') {
res.writeHead(200);
res.end(JSON.stringify({ message: 'Hello from GET!' }));
} else if (method === 'POST' && url === '/data') {
let body = '';
// Collect the POST data
req.on('data', chunk => {
body += chunk.toString();
});
// Handle end of data
req.on('end', () => {
const parsedData = JSON.parse(body);
res.writeHead(200);
res.end(JSON.stringify({
message: 'Received POST data!',
data: parsedData
}));
});
} else {
res.writeHead(404);
res.end(JSON.stringify({ error: 'Not found' }));
}
});
server.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});

4.2 Testing It

  • GET request:
    Visit http://localhost:3000/ in your browser β†’ responds with JSON.

  • POST request (e.g. using curl or Postman):

Terminal window
curl -X POST http://localhost:3000/data \
-H "Content-Type: application/json" \
-d '{"name":"Nadith", "age":17}'