Inside this article!
- Introduction
- Installation
- Hello World
- Simple Server
- Serve String
- Serve HTML
- Serve JSON
- Serve PDF
- Serve Audio
- Serve Video
- Summary
Introduction
Node.js is a platform (server-side) which is built on google chrome's javascript v8 engine. It is open source , cross platform and is capable of generating real time web applications. It uses event-driven, non-blocking I/O operation model which makes it efficient and light-weight. It is developed by Ryan Dahl with the team of other developers working at joyent in 2009. Its initial release only supports linux. It is written in C,C++ and javascript. It's package ecosystem 'NPM' is the largest ecosystem of open source libraries in the world.
Node.js是基于Google chrome的javascript v8引擎构建的平台(服务端)。它是开源的,跨平台的,并且能够生成实时web应用程序。它使用事件驱动,无阻塞的I/O操作模型,从而使其高效,轻巧。它是由Ryan Dahl与其他开发人员团队于2009年在Joyent合作开发的。它的初始版本仅支持linux。它是用C,C ++和javascript编写的。它的软件包生态系统“ NPM”是世界上最大的开源库生态系统。
Installation
Based on the architecture of your Operating System, you can download the latest version of node.js from the downloads page of node's official website :
Once you are done with the download , open any text editor and start coding. Some examples of text editors are Atom , Notepad++ , Visual Studio Code , Sublime Text .
All node.js files are stored with the extension ".js" just like javascript.
Hello World in Node.js
Let's follow the ritual of programming and start by creating a program which will print hello world
on the console as output. This code-snippet is as simple as it can be.
// file-name : hello-world-in-node.js
console.log('hello world');
You can run the above code using the following command :
node hello-world-in-node.js
Create a Server in Node.js
- Node provide us with the inbuilt
http
module which we can use to create the server. Get the access to the module by usingrequire
- Mention the host i.e. localhost (127.0.0.1) to serve it locally.
- Mention the port. We are using port : 3000 for our example.
- Create a server using the
createServer()
method.createServer()
method takes a callback function as arguments. This callback is executed each time a request is received. - The two arguments of
createServer()
method arerequest
: which contains all the information related to client's request such as URL, custom headers , client info , etc.response
: which is used to return the data back to the client. -
response.writeHead
is an inbuilt method which is used to send the
status code and the MIME type - And after that we are just Printing the value on the console using
console.log()
function. -
response.end()
is an inbuilt function which is used to tell the server that the request has been fulfilled. Along with that we can also send one response using this. -
server.listen()
is an inbuilt method used to bind to the port an start listening for incoming connections.
// simple-server-in-nodejs.js
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((request, response) => {
response.writeHead(200, {'Content-Type': 'text/plain'});
console.log('server working');
response.end('Server Working Success!\n');
});
server.listen(port, host, (error) => {
if (error) {
return console.log('Error occured: ', error);
}
console.log(`Server running at http://${hostname}:${port}/`);
});
Create a Server in Node.js and Server a String
response.write()
: It is the inbuilt method which is used to send the response. In the above section we used response.end()
to send the response but we can only send one response using this. however , we can send as many responses as we want using response.write()
method. Now Let's see how we can serve a string in an http server in node.js.
const http = require('http');
const hostname = '127.0.0.1'
const port = 3000;
const server = http.createServer((request, response) => {
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello World!");
response.end();
});
server.listen(port, host, (error) => {
if (error) {
return console.log('Error occured : ', error );
}
console.log('server is listening on ' + hostname + ':'+ port);
});
Create a Server in Node.js and Server HTML
In the previous section we learned how we can serve a string using node.js but in practical applications we hardly need to serve the string. In most of the cases , we serve html files via the node.js server. So let's see how we can serve a html file using node.js
// server-html.js
const http = require('http');
const fs = require('fs');
http.createServer((request, response) => {
console.log('Port number: 3000');
// Change the MIME type from 'text/plain' to 'text/html'
res.writeHead(200, {'Content-Type': 'text/html'});
// reading the content file
fs.readFile('index.html', (err, data) => {
// checking for errors
if (err)
throw err;
console.log('Operation Success');
// sending the response
res.end(data);
});
}).listen(3000);
index.html
<h1>
Finally I am serving an HTML File via a server.
But it is not recommended for production.
</h1>
Create a Server in node.js and Server JSON
There may be scenarios when the response which we need to send is not a plain text , For REST Api's we usually have to send JSON response. So , let's see how we can serve JSON in a node.js server
// server-json.js
const http = require('http');
http.createServer((req, res) => {
console.log('Port Number: 3000');
res.writeHead(200, {'Content-Type': 'application/json'});
let json_response = {
status: 200,
message: 'successful',
result: ['sunday', 'monday', 'tuesday', 'wednesday'],
code: 2000
};
res.end(JSON.stringify(json_response));
}).listen(3000);
Create a Server in Node.js and Server pdf
// server-pdf.js
const http = require('http');
const fs = require('fs');
http.createServer((req, res) => {
console.log('Port Number: 3000');
fs.readFile('index.pdf', (err, data) => {
if (err) {
throw err;
} else {
res.writeHead(200, {'Content-Type': 'application/pdf'});
res.write(data);
res.end();
}
});
}).listen(3000);
Create a Server in Node.js and server Audio/mp3
// server-mp3.js
const http = require('http');
const fs = require('fs');
http.createServer((req, res) => {
console.log('Port Number: 3000');
fs.exists('audio.mp3', (exists) => {
if (exists) {
res.writeHead(200, {'Content-Type': 'audio/mp3'});
let rstream = fs.createReadStream('audio.mp3');
stream.pipe(res);
} else {
res.end('404');
}
});
}).listen(3000);
Create a Server in node.js and server video/mp4
And we have saved the best for the last. We can also serve videos using a simple node.js server. All you have to do is change the MIME type as shown below :
// server-mp4.js
const http = require('http');
const fs = require('fs');
http.createServer((req, res) => {
console.log('Port Number: 3000');
fs.exists('video.mp4', (exists) => {
if (exists) {
res.writeHead('200', {'Content-Type': 'video/mp4'});
let rstream = fs.createReadStream('video.mp4');
rstream.pipe(res);
} else {
res.send('404');
res.end();
}
});
});
Summary
In this part of the node.js series **30 days of node**
we learned about node.js server
. Also a basic introduction to node.js and how we can install node.js. Then an hello world
example in node.js. Then we learned how to create a simple http server in node.js and serve the following :
- Serve a String using node.js server
- Serve html file using node.js server
- Serve JSON using node.js server
- Serve pdf file using node.js server
- Serve mp3 file using node.js server
- Serve video/mp4 file using node.js server