Learning by Examples
Node.js allows us to run JavaScript on server side.Example
var http = require('http'); http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello World!'); }).listen(8080);Examples Running in the Command Line Interface
console.log('The result is displayed in the Command Line Interface');Node.js Reference
Here is a list of the built-in modules of Node.js version 6.10.3:
Module | Description |
---|---|
assert | Provides a set of assertion tests |
buffer | To handle binary data |
child_process | To run a child process |
cluster | To split a single Node process into multiple processes |
crypto | To handle OpenSSL cryptographic functions |
dgram | Provides implementation of UDP datagram sockets |
dns | To do DNS lookups and name resolution functions |
domain | Deprecated. To handle unhandled errors |
events | To handle events |
fs | To handle the file system |
http | To make Node.js act as an HTTP server |
https | To make Node.js act as an HTTPS server. |
net | To create servers and clients |
os | Provides information about the operation system |
path | To handle file paths |
punycode | Deprecated. A character encoding scheme |
querystring | To handle URL query strings |
readline | To handle readable streams one line at the time |
stream | To handle streaming data |
string_decoder | To decode buffer objects into strings |
timers | To execute a function after a given number of milliseconds |
tls | To implement TLS and SSL protocols |
tty | Provides classes used by a text terminal |
url | To parse URL strings |
util | To access utility functions |
v8 | To access information about V8 (the JavaScript engine) |
vm | To compile JavaScript code in a virtual machine |
zlib | To compress or decompress files |
node myfirst.js
and hit enter.
Now, your computer works as a server!
If anyone tries to access your computer on port 8080, they will get a "Hello World!" message in return!
Start your internet browser, and type in the address: http://localhost:8080
require()
function with the name of the module:
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);
exports
keyword to make properties and methods available outside the module file.
Save the code above in a file called "myfirstmodule.js"
./
to locate the module, that means that the module is located in the same folder as the Node.js file.
Save the code above in a file called "demo_module.js", and initiate the file:
Initiate demo_module.js:
C:\Users\Your Name>node demo_module.js
If you have followed the same steps on your computer, you will see the same result as the example: http://localhost:8080
require()
method:
var http = require('http');
createServer()
method to create an HTTP server:
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.
Save the code above in a file called "demo_http.js", and initiate the file:
Initiate demo_http.js:
C:\Users\Your Name>node demo_http.js
If you have followed the same steps on your computer, you will see the same result as the example: http://localhost:8080
res.writeHead()
method is the status code, 200 means that all is OK, the second argument is an object containing the response headers.
http.createServer()
has a req
argument that represents the request from the client, as an object (http.IncomingMessage object).
This object has a property called "url" which holds the part of the url that comes after the domain name:
demo_http_url.js
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(req.url);
res.end();
}).listen(8080);
Save the code above in a file called "demo_http_url.js" and initiate the file:
Initiate demo_http_url.js:
C:\Users\Your Name>node demo_http_url.js
If you have followed the same steps on your computer, you should see two different results when opening these two addresses:
http://localhost:8080/summer
Will produce this result:
/summer
http://localhost:8080/winter
Will produce this result:
/winter
require()
method:
var fs = require('fs');
Common use for the File System module:
Read files
Create files
Update files
Delete files
Rename files
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:
var http = require('http');
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);
res.end();
});
}).listen(8080);
Save the code above in a file called "demo_readfile.js", and initiate the file:
C:\Users\Your Name>node demo_readfile.js
If you have followed the same steps on your computer, you will see the same result as the example: http://localhost:8080
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:
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:
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:
fs.appendFile()
fs.writeFile()
The fs.appendFile()
method appends the specified content at the end of the specified file:
fs.writeFile()
method replaces the specified file and content:
fs.unlink()
method.
The fs.unlink()
method deletes the specified file:
fs.rename()
method.
The fs.rename()
method renames the specified file:
require()
method:
var url = require('url');
Parse an address with the url.parse()
method, and it will return a URL object with each part of the address as properties:
C:\Users\My Name\node_modules\upper-case
require()
method. In addition, all event properties and methods are an instance of an EventEmitter object. To be able to access these properties and methods, create an EventEmitter object:
var events = require('events');
var eventEmitter = new events.EventEmitter();
emit()
method.
var events = require('events');
var eventEmitter = new events.EventEmitter();
//Create an event handler:
var myEventHandler = function () {
console.log('I hear a scream!');
}
//Assign the event handler to an event:
eventEmitter.on('scream', myEventHandler);
//Fire the 'scream' event:
eventEmitter.emit('scream');
Run example »
parse()
method's callback function.
To move the file to the folder of your choice, use the File System module, and rename the file: