Repo made to learn NodeJS. This will also include making restful APIs and dealing with requests and responses.
text/htmlapplication/jsonimage/jpegimage/pngimage/gifaudio/mpegvideo/mp4application/javascripttext/csstext/plain
res.setHeader(name, value)- Sets a response header.res.getHeader(name)- Retrieves a specific response header.res.removeHeader(name)- Removes a response header.res.writeHead(statusCode, headers)- Sets status code and multiple headers at once.
res.write(chunk)- Writes data to the response body.res.end([data])- Signals the response is complete, optionally sending a final chunk of data.
res.statusCode = number- Sets the HTTP status code.res.statusMessage = "message"- Customizes the status message.
res.flushHeaders()- Forces headers to be written immediately.res.hasHeader(name)- Checks if a header exists.
GET- Retrieves data from the server.POST- Sends data to the server to create a new resource.PUT- Updates or replaces an existing resource on the server.HEAD- Similar toGET, but only retrieves headers (no body).DELETE- Removes a resource from the server.PATCH- Partially updates an existing resource.OPTIONS- Returns the supported HTTP methods for a resource.
Reference to Article: The 7 Methods
const http = require("http");
const server = http.createServer((req, res) => {
res.setHeader("Content-Type", "text/plain");
res.end("Hello World\n");
});
const PORT = 3000;
server.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}/`);
});"scripts": {
"start": "node server.js",
"dev": "nodemon server.js"
}
# This will run nodemon server.js for updates on save
npm run dev
const http = require("http"); // importing the http module from node:http
const arrayList = [
{ id: 1, item: "item 1" },
{ id: 2, item: "item 2" },
{ id: 3, item: "item 3" },
{ id: 4, item: "item 4" },
]; // array list
const server = http.createServer((req, res) => {
// using the createServer method from http module
res.setHeader("Content-Type", "application/json"); // setting the response for the header
res.end(
// ending/final response
JSON.stringify(
// This is to convert object to string, err: The "chunk" argument must be of type string or an instance of Buffer or Uint8Array.
{
sucess: true,
method: req.method,
data: arrayList,
}
)
);
});
const PORT = 3000; // setting port number
server.listen(PORT, () => {
// listen to the port and then console log message
console.log(`Server running at http://localhost:${PORT}/`);
});
- Download and install the following npm packages:
# This will install express and we need to make a .env file
npm install express dotenv- Now we alter our code to use NodeJS w/ Express.
server.js
const http = require("http"); // importing the http module from node:http
require("dotenv").config(); // import environment variables from .env file
const app = require("./app"); // import data from index.js
const server = http.createServer(app); // throw data from express app to http server
server.listen(process.env.PORT, () => {
// listen to the port and then console log message
console.log(`Server running at http://localhost:${process.env.PORT}/`);
});app/index.js
const express = require("express");
// import { express } from 'express';
const app = express();
app.get("/", (req, res) => {
// use '/' route
res.status(200).json({
// get status 200 - success and return data into JSON
message: "GET - root",
metadata: {
hostname: req.hostname,
method: req.method,
},
});
});
module.exports = app; // export app, used in server.js filenpm i -D jest
math.test.js
- Writing tests for math objects.
const { add, subtract, multiply, divide, sqrt, max } = require("./math");
describe("Testing basic math objects", () => {
test("Should add two numbers", () => {
const result = add(1, 2);
expect(result).toBe(3);
});
test("Should subtract two numbers", () => {
const result = subtract(2, 1);
expect(result).toBe(1);
});
test("Should multiply two numbers", () => {
const result = multiply(2, 3);
expect(result).toBe(6);
});
test("Should divide two numbers", () => {
const result = divide(6, 3);
expect(result).toBe(2);
});
});
describe("Testing advanced math objects", () => {
test("Should find the sqrt of a number", () => {
const result = sqrt(4);
expect(result).toBe(2);
});
test("Should find the max of two numbers", () => {
const result = max(1, 2);
expect(result).toBe(2);
});
});math.js
// >>> Basic Math Objects
const add = (a, b) => {
return a + b;
};
const subtract = (a, b) => {
return a - b;
};
const multiply = (a, b) => {
return a * b;
};
const divide = (a, b) => {
return a / b;
};
add(1, 2); // result should be 3
subtract(2, 1); // result should be 1
multiply(2, 3); // result should be 6
divide(6, 3); // result should be 2
// >>> Advanced Math Objects
const sqrt = (a) => {
return Math.sqrt(a);
};
const max = (a, b) => {
return Math.max(a, b);
};
sqrt(4); // result should be 2
max(1, 2); // result should be 2
module.exports = {
add,
subtract,
multiply,
divide,
sqrt,
max,
};