Creating Server Using Only NodeJS:-
const http = require('http');
const server = http.createServer(function(req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
var message = 'Hurrah!! I created my first server with NodeJS.\n',
version = 'NodeJS ' + process.versions.node + '\n',
response = [message, version].join('\n');
res.end(response);
});
server.listen('3000', '127.0.0.1');
Creating your first real application:-
STEPS:-
- Create:- index.html
- Create:- server.js
- Run:- node server.js
index.html
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Hello I am Index File to be shown in NodeJS server</title>
</head>
<body>
<h1>Hello from Index Page</h1>
<p>Hello world!! I am Index Page. I am the page which will be rendered in the server which you just created using NodeJS</p>
</body>
</html>
server.js
const http = require('http');
const fs = require('fs');
let htmlContent = fs.readFileSync('./index.html');
const server = http.createServer(function(req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(htmlContent);
});
server.listen('3000', '127.0.0.1');
Now both files are created and ready to go. Now go to your command prompt and navigate to the file and run the command node server.js
**NOTE:- ** In the above file server.js, Content-Type: text/html.
Creating your first real application with different Routes in URL:-
const http = require('http');
const fs = require('fs');
const server = http.createServer(function(req, res) {
if(req.url === '/') {
res.writeHead(200, {'Content-Type': 'text/html'});
let htmlContent = fs.readFileSync('./index.html');
res.end(htmlContent);
} else if (req.url === '/json-user') {
res.writeHead(200, {'Content-Type': 'application/json'});
let jsonContent = fs.readFileSync('./json-user.json');
res.end(jsonContent);
} else if (req.url === '/js-user') {
res.writeHead(200, {'Content-Type': 'application/json'});
let javascriptObject = fs.readFileSync('./js-user.js');
let jsonContent = JSON.stringify(javascriptObject);
res.end(jsonContent);
} else {
res.writeHead(404);
res.end();
}
});
server.listen('3000', '127.0.0.1');
This was just to show that we can create our app by just using NodeJS. But in real life for routing this way will be much more complex as the number of URL increases for our site. Thus, we use ExpressJS library to handle this URL routing. That we will come to know in our next blog.
@abcd 1 days ago
Aquí los que apoyamos a Los del limit desde sus inicios..