Export
Here I oppose three different ways to export modules on node.js
Lets say we want to export three functions from a file called count.js
var counter = function(arr){
return 'There are '+ arr.length + ' elements';
}
//This can be done by using backticks
var adder = function(a,b){
return `The sum of two numbers is ${a+b}`;
}
var pi = 3.142;
First way
//Export
module.exports.counter = counter;
module.exports.adder = adder;
module.exports.pi = pi;
Second way
module.exports.counter = function(arr){ return 'There are '+ arr.length + ' elements'; } module.exports.adder = function(a,b){ return `The sum of two numbers is ${a+b}`; } module.exports.pi = 3.142;
Third way
module.exports = { counter:counter, adder:adder, pi:pi }
Require the file into app.js and run the command node app.js.
var count = require('./count'); console.log( count.counter(['a','b','c']) ); console.log( count.adder(5,6) ); console.log( count.adder( count.pi,6) );
Emitting Events
Node.js has build in modules who work like custom modules. Two of them are events and utils.
Events Module example
var events = require('events'); var myEmitter = new events.EventEmitter(); myEmitter.on('someEvent', function(msg){ console.log(msg); }); myEmitter.emit('someEvent','the event was emitted');
Events Module and Utils Module example
var events = require('events'); var util = require('util'); var Person = function(name){ this.name = name; }; util.inherits(Person, events.EventEmitter); var george = new Person('George'); var vivian = new Person('Vivian'); var peter = new Person('Peter'); var people = [george,vivian,peter]; people.forEach(function(person){ person.on('speak', function(msg){ console.log(person.name + ' said: ' + msg); }); }); george.emit('speak', 'I\'m a young boy'); vivian.emit('speak', 'I want money'); peter.emit('speak', 'Jazz music is cool');
Reading and Writing Files
There are two ways to read and write file.
The synchronous method reads all file is read first before going through other code of the script.
The asynchronous method is called when the proccess of the script is complete.It’s not blocking the execution of the script.
Synchronous Read & Write
var fs = require('fs');
//You can give the full path of the file
var readMe = fs.readFileSync('file.txt','utf8');
console.log(readMe);
fs.writeFileSync('writeFile.txt', readMe);
Asynchronous Read & Write
var fs = require('fs');
fs.readFile('writeFile.txt','utf8', function(err, data){
console.log(data);
});
//It writes the data of the writeFile.txt to writtenFile.txt
fs.readFile('writeFile.txt','utf8', function(err, data){
fs.writeFile('writtenFile.txt', data);
});
Delete Files
var fs = require('fs');
//If the file does not exist an error will be raised
fs.unlink('writeFile.txt');
Directories
Node can create and remove directories
Synchronous
fs.mkdirSync('myNewDirectory'); fs.rmdirSync('myNewDirectory');
Asynchronous
fs.mkdir('myNewDirectory', function(){
fs.readFile('writtenFile.txt','utf8', function(err,data){
fs.writeFile('./myNewDirectory/writeMe.txt', data);
});
});
//To remove a directory we first must remove it's contents
fs.unlink('./myNewDirectory/writeMe.txt', function(){
fs.rmdir('myNewDirectory');
});
Creating a Server
Run the file with this code and type in the url bar 127.0.0.1:3000
var http = require('http');
var server = http.createServer(function(req, res){
//this message appears when loading the page
console.log( 'request was made: '+ req.url );
res.writeHead(200, {'Content_Type': 'text/plain'});
res.end('Hey Pita!');
});
server.listen(3000,'127.0.0.1');
console.log('yo');
Readable/Writable Streams
Readable Stream
var http = require('http'); var fs = require('fs'); var myReadStream = fs.createReadStream(__dirname+'/readMe.txt', 'utf8'); myReadStream.on('data', function(chunk){ console.log('new chuck received:'); console.log(chunk); });
Writable Stream
var http = require('http'); var fs = require('fs'); var myReadStream = fs.createReadStream(__dirname+'/readMe.txt', 'utf8'); var myWriteStream = fs.createWriteStream(__dirname+'/writeMe.txt'); myReadStream.on('data', function(chunk){ console.log('new chuck received:'); myWriteStream.write(chunk); });
Pipes
Example 1
Writing with a pipe
var http = require('http');
var fs = require('fs');
var myReadStream = fs.createReadStream(__dirname+'/readMe.txt', 'utf8');
var myWriteStream = fs.createWriteStream(__dirname+'/writeMe.txt');
//can only use this method on readable streams
myReadStream.pipe(myWriteStream);
Example 2
Send data to the browser with a pipe
var http = require('http'); var fs = require('fs'); var server = http.createServer(function(req, res){ console.log( 'request was made: '+ req.url ); res.writeHead(200, {'Content_Type': 'text/plain'}); var myReadStream = fs.createReadStream(__dirname+'/readMe.txt', 'utf8'); //send data down the stream to the client myReadStream.pipe(res); }); server.listen(3000,'127.0.0.1'); console.log('yo'); //go to 127.0.0.1:3000
Read html Pages
var http = require('http'); var fs = require('fs'); var server = http.createServer(function(req, res){ console.log( 'request was made: '+ req.url ); //different content type res.writeHead(200, {'Content_Type': 'text/html'}); var myReadStream = fs.createReadStream(__dirname+'/index.html', 'utf8'); myReadStream.pipe(res); }); server.listen(3000,'127.0.0.1'); console.log('yo'); //Go to 127.0.0.1:3000
Read JSON
var http = require('http'); var fs = require('fs'); var server = http.createServer(function(req, res){ console.log( 'request was made: '+ req.url ); //different content type res.writeHead(200, {'Content_Type': 'application/json'}); var myJson = { name: 'Petros', job: 'Web developer', age: '35' }; res.end(JSON.stringify(myJson)); }); server.listen(3000,'127.0.0.1'); console.log('yo'); //go to 127.0.0.1:3000
Basic Routing
In order for this to work you have to create the corresponding html pages!
var http = require('http'); var fs = require('fs'); var server = http.createServer(function(req, res){ console.log( 'request was made: '+ req.url ); if(req.url === '/home' || req.url === '/'){ res.writeHead(200, {'Content_Type': 'text/html'}); fs.createReadStream(__dirname + '/index.html').pipe(res); } //create also a contact.html file else if(req.url === '/contact'){ res.writeHead(200, {'Content_Type': 'text/html'}); fs.createReadStream(__dirname + '/index.html').pipe(res); } else if(req.url === '/siteland'){ var persons = [{name: 'George', age:4}, {name: 'Vivian', age:36}]; res.writeHead(200, {'Content_Type': 'application/json'}); res.end(JSON.stringify(persons)); } else{ //404 response type res.writeHead(404, {'Content_Type': 'text/html'}); fs.createReadStream(__dirname + '/404.html').pipe(res); } }); server.listen(3000,'127.0.0.1'); console.log('yo');
Express framework
To install type the command:
npm install express
To also update the package.json file dependencies type:
npm install express -save
var express = require('express'); var app = express(); app.get('/', function(req, res){ res.send('this is the homepage'); }); app.get('/contact', function(req, res){ res.send('this is contact page'); }); app.get('/profile/:id', function(req, res){ res.send('Your id is '+ req.params.id); }); app.listen(3000);
Template engines(ejs)
Ejs is one of the template engines that work with express. It’s desault directory is views.
Create views directory and inside it create profile.ejs file. This is like an html template folder and the dynamic content goes inside asp like tage <%= content %>.
var express = require('express'); var app = express(); app.set('view engine', 'ejs'); app.get('/', function(req, res){ res.sendFile(__dirname + '/index.html'); }); app.get('/contact', function(req, res){ res.sendFile(__dirname + '/contact.html'); }); app.get('/profile/:id', function(req, res){ var data = {age: 29, job: 'Web developer'}; res.render('profile', {id: req.params.id, data: data} ); }); app.listen(3000);
Referance
The Net Ninja you tube channel