Node introduction
Node js role -- Run Server - Create Server and Listen to incoming requests
- Business Logic - Handle the request, Validate Input Connect to Database
- Response -Return response -> Html JSON
console.log("Hello from Node...!!!");
//normal file read and write
const fs = require("fs");
fs.writeFileSync("file.txt", "Hello from Node-> Im Yasas");
fs.readFile("file.txt", "utf8", function (err, data) {
if (err) {
return console.log(err);
}
console.log(data);
});
//REPL -> direct input way in node shell (jst type node in the terminal)
Read
Evaluate
Print
Loop
Normal Http Server creating ..> Node Core
const http = require('http');
const server = http.createServer((request, response) => {
console.log(request); //we can see here method headers etc...
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end('Hello World');
});
server.listen(3000);
console.log("Server running at http://127.0.0.1:3000/");
/*If you want to quit
process.exit(); <- If there is a request came,
we can use this as quit method
*/
Now Advanced server -> Handling redirections(Routing),
data buffers and file writes, etc..
const http = require("http");
const fs = require("fs"); // file sysytem core module
//New Http server creating
const server = http.createServer((request, response) => {
const url = request.url;
const method = request.method;
//Redirection
// (In Express..this will be much easier)
if (url === "/") {
response.write("<html>");
response.write("<head><title>Enter Message</title></head>");
response.write('<body><h1> <center> <form action="/message" method="POST">');
response.write('<input type="text" name="message">');
response.write('<button type="submit">Send</button></form>');
response.write('</center></h1></body>');
response.write("</html>");
return response.end();
}
if (url === "/message" && method === "POST") {
const body = [];
//event handling (listners)
//listning every incoming data chunks
request.on("data", (chunk) => {
console.log("-----chunk-----");
console.log(chunk);
body.push(chunk);
console.log("-----body-----");
console.log(body);
});
/*event listener - end - this will be fired
once it's done parsing the incoming request data*/
return request.on("end", () => {
/*now we have to work with buffers
buffer.concat ->create a new buffer and add all chunks from the body onto it
toString() -> because incoming data is text.
(if a file is there we have to do something different)*/
const parsedBody = Buffer.concat(body).toString();
//this will print actual data
console.log(parsedBody);
//taking the message without = and the key (name field in the form)
const message = parsedBody.split("=")[1];
/*now we write the data into a file
we need import file system
fs.writeFileSync("message.txt", message); <-this is not used cuz
sync->synchronous - block code execution until the file is created
we need unblocked callbacks (newer block the call execution)
so we used->*/
fs.writeFile("message.txt", message, (err) => {
//can handle err
console.log(err);
response.statusCode = 302;
response.setHeader("Location", "/new");//setting new location(Routing)
console.log("finished....");
return response.end(); //make sure to return or else
//it will execute below codes also
});
//setting status code for redirection
});
}
response.setHeader("Content-Type", "text/html");
response.write("<html>");
response.write("<head><title>This is my first Node js Server</title></head>");
response.write(
"<body><h1> <center> Welcome to the Yasas Server </center></h1></body>"
);
response.write("</html>");
response.end();
//console.log(response);
});
server.listen(3000);
console.log("Server running at http://127.0.0.1:3000/");
Common facts
there is no anything like request. data > because requests are streames
(Stream of data packets/chunks)
we have to work them with buffers (Like bus stops)
ex:- <Buffer 6d 65 73 73 61 67 65 3d 68 65 6c 6c 6f>
event listeners are asynchronous - not blocking any other codes
using express js these things will be much easier

0 Comments