Node.js
What is Node.js?
Node.js can be defined as a dynamic, cross-platform and open-source JavaScript framework or runtime environment that is built on the Google Chrome JavaScript V8 engine. Developed by Ryan Dahl in 2009, Node.js was initially implemented as a client-side scripting language. Nowadays, it is used to execute JavaScript code and scripts that run server-side to create dynamic web pages. The latest version of Node.js is 10.10.0.
Node.js Features and Benefits
Most web developers
implement Node.js due to its amazing and powerful features. Some of the
features of Node.js are:
·
Faster code execution
·
Highly scalable
·
Non-blocking APIs
·
No buffering
With such wonderful
features, Node.js is widely used for creating server-side and networking
applications. The following are the key areas where Node.js is widely used:
·
I/O-bound applications
·
Data streaming
applications
·
Data-intensive real-time
applications (DIRT)
·
JSON API-based
applications
·
Single-page applications
There are many companies currently using Node.js
such as eBay, General Electric, GoDaddy, Microsoft, PayPal, Uber, Wikipins,
Yahoo!, IBM, Groupon, LinkedIn, Netflix and many others.
What Can Node.js Do?
- Node.js
can generate dynamic page content
- Node.js
can create, open, read, write, delete, and close files on the server
- Node.js
can collect form data
- Node.js
can add, delete, modify data in your database
Node.js can be defined as a dynamic, cross-platform and open-source JavaScript framework or runtime environment that is built on the Google Chrome JavaScript V8 engine. Developed by Ryan Dahl in 2009, Node.js was initially implemented as a client-side scripting language. Nowadays, it is used to execute JavaScript code and scripts that run server-side to create dynamic web pages. The latest version of Node.js is 10.10.0.
Node.js Features and Benefits
Most web developers
implement Node.js due to its amazing and powerful features. Some of the
features of Node.js are:
·
Faster code execution
·
Highly scalable
·
Non-blocking APIs
·
No buffering
With such wonderful
features, Node.js is widely used for creating server-side and networking
applications. The following are the key areas where Node.js is widely used:
·
I/O-bound applications
·
Data streaming
applications
·
Data-intensive real-time
applications (DIRT)
·
JSON API-based
applications
·
Single-page applications
There are many companies currently using Node.js
such as eBay, General Electric, GoDaddy, Microsoft, PayPal, Uber, Wikipins,
Yahoo!, IBM, Groupon, LinkedIn, Netflix and many others.
What Can Node.js Do?
- Node.js
can generate dynamic page content
- Node.js
can create, open, read, write, delete, and close files on the server
- Node.js
can collect form data
- Node.js
can add, delete, modify data in your database
Node is
primarily made up of JavaScript and the event loop.
The
event loop is basically a program that waits for events and dispatches them
when they happens. One other important fact you might know is that JavaScript
is single thread and so is Node.
Unlike other languages that require a new thread or process for every single request, NodeJs takes all requests and then delegates most of the work to other system workers. There’s something called a Libuv library which handles this work effectively with help from the OS kernel. When the background workers are done doing their work, they emit events to NodeJs callbacks registered on that event.
This brings us to callbacks. They are basically functions passed into other functions as arguments and are called when certain conditions occur.
Download Node.js
The official Node.js website has installation instructions for
Node.js: https://nodejs.org
Getting Started
Once you
have downloaded and installed Node.js on your computer, let's try to display
"Hello World" in a web browser.
var http
= require('http');
http.createServer(function (req,
res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('Hello
World!');
}).listen(8080);
Include Modules
To include a module, use the require()
function with the name of the module:
Example
var http = require('http');
Now your application has access to the HTTP module, and is able to create a server:
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('Hello World!');
}).listen(8080);
Node.js as a Web Server
The HTTP module can create an HTTP server that listens to server ports and gives a response back to the client.
Use the createServer()
method to create an HTTP server:
Example
var http = require('http');
//create a server object:
http.createServer(function (req, res) {
res.write('Hello World!'); //write a response to the client
res.end(); //end the response
}).listen(8080); //the server object listens on port 8080
The function passed into the http.createServer()
method, will be executed when someone tries to access the computer on port 8080.
Add an HTTP Header
If the response from the HTTP server is supposed to be displayed as HTML, you should include an HTTP header with the correct content type:
Example
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('Hello World!');
res.end();
}).listen(8080);
res.writeHead()
method is the status code, 200 means that all is OK, the second argument is an object containing the response headers.Node.js as a File Server
The Node.js file system module allows you to work with the file system on your computer.
To include the File System module, use the require()
method:
var fs = require('fs');
Common use for the File System module:
- Read files
- Create files
- Update files
- Delete files
- Rename files
Read Files
The fs.readFile()
method is used to read files on your computer.
Assume we have the following HTML file (located in the same folder as Node.js):
demofile1.html
<html>
<body>
<h1>My Header</h1>
<p>My paragraph.</p>
</body>
</html>
Create a Node.js file that reads the HTML file, and return the content:
Example
var fs = require('fs');
http.createServer(function (req, res) {
fs.readFile('demofile1.html', function(err, data) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
return res.end();
});
}).listen(8080);
Create Files
The File System module has methods for creating new files:
fs.appendFile()
fs.open()
fs.writeFile()
The fs.appendFile()
method appends specified content to a file. If the file does not exist, the file will be created:
Example
Create a new file using the appendFile() method:
var fs = require('fs');
fs.appendFile('mynewfile1.txt', 'Hello content!', function (err) {
if (err) throw err;
console.log('Saved!');
});
he fs.open()
method takes a "flag" as the second argument, if the flag is "w" for "writing", the specified file is opened for writing. If the file does not exist, an empty file is created:
Example
Create a new, empty file using the open() method:
var fs = require('fs');
fs.open('mynewfile2.txt', 'w', function (err, file) {
if (err) throw err;
console.log('Saved!');
});
The fs.writeFile()
method replaces the specified file and content if it exists. If the file does not exist, a new file, containing the specified content, will be created:
Example
Create a new file using the writeFile() method:
var fs = require('fs');
fs.writeFile('mynewfile3.txt', 'Hello content!', function (err) {
if (err) throw err;
console.log('Saved!');
});
Delete Files
To delete a file with the File System module, use the fs.unlink()
method.
The fs.unlink()
method deletes the specified file:
Example
Delete "mynewfile2.txt":
var fs = require('fs');
fs.unlink('mynewfile2.txt', function (err) {
if (err) throw err;
console.log('File deleted!');
});
Rename Files
To rename a file with the File System module, use the fs.rename()
method.
The fs.rename()
method renames the specified file:
Example
Rename "mynewfile1.txt" to "myrenamedfile.txt":
var fs = require('fs');
fs.rename('mynewfile1.txt', 'myrenamedfile.txt', function (err) {
if (err) throw err;
console.log('File Renamed!');
});
Comments
Post a Comment