Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
113 views

Lecture # 5 Introduction To Node - Js (Part II) : by Dr. Sidra Sultana

The document discusses Node.js and the file system module. It covers how to: 1) Read, create, update, delete, and rename files using methods like fs.readFile(), fs.writeFile(), and fs.rename(). 2) Download and use Node.js packages/modules from NPM like Formidable for file uploads. 3) Upload files to a server with Node.js by creating an upload form and parsing the uploaded file.

Uploaded by

Danial Ahmad
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
113 views

Lecture # 5 Introduction To Node - Js (Part II) : by Dr. Sidra Sultana

The document discusses Node.js and the file system module. It covers how to: 1) Read, create, update, delete, and rename files using methods like fs.readFile(), fs.writeFile(), and fs.rename(). 2) Download and use Node.js packages/modules from NPM like Formidable for file uploads. 3) Upload files to a server with Node.js by creating an upload form and parsing the uploaded file.

Uploaded by

Danial Ahmad
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 29

Lecture # 5

Introduction to Node.js (Part II)


By Dr. Sidra Sultana
Node.js File System Module
 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 demofile1.html (located in the same folder as
Node.js):
<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 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);
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!');
});
Create Files cont’d
 The 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!');
});
Update Files
The File System module has methods for updating files:
 fs.appendFile()
 fs.writeFile()
 The fs.appendFile() method appends the specified content at the end of the specified
file:
 Example
Append "This is my text." to the end of the file "mynewfile1.txt":
var fs = require('fs');
fs.appendFile('mynewfile1.txt', ' This is my text.', function (err) {
  if (err) throw err;
  console.log('Updated!');
});
 The fs.writeFile() method replaces the specified file and content:
 Example
Replace the content of the file "mynewfile3.txt":
var fs = require('fs');
fs.writeFile('mynewfile3.txt', 'This is my text', function (err) {
  if (err) throw err;
  console.log('Replaced!');
});
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!');
});
Node.js NPM
 NPM is a package manager for Node.js packages, or
modules if you like.
 www.npmjs.com hosts thousands of free packages to
download and use.
 The NPM program is installed on your computer when
you install Node.js
 NPM is already ready to run on your computer!
What is a Package?
 A package in Node.js contains all the files you need for a
module.
 Modules are JavaScript libraries you can include in your
project.
Download a Package
 Downloading a package is very easy.
 Open the command line interface and tell NPM to download
the package you want.
 I want to download a package called "upper-case":
 Download "upper-case":
 C:\Users\Your Name>npm install upper-case
 Now you have downloaded and installed your first package!
 NPM creates a folder named "node_modules", where the
package will be placed. All packages you install in the future
will be placed in this folder.
 My project now has a folder structure like this:
 C:\Users\My Name\node_modules\upper-case
Using a Package
 Once the package is installed, it is ready to use.
 Include the "upper-case" package the same way you include any other
module:
var uc = require('upper-case');
 Create a Node.js file that will convert the output "Hello World!" into
upper-case letters:
 Example
var http = require('http');
var uc = require('upper-case');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/html'});
  res.write(uc("Hello World!"));
  res.end();
}).listen(8080);
Node.js Upload Files
The Formidable Module
 There is a very good module for working with file
uploads, called "Formidable".
 The Formidable module can be downloaded and installed
using NPM:
 C:\Users\Your Name>npm install formidable
 After you have downloaded the Formidable module, you
can include the module in any application:
 var formidable = require('formidable');
Upload Files
 Now you are ready to make a web page in Node.js that lets the user
upload files to your computer:
 Step 1: Create an Upload Form
 Create a Node.js file that writes an HTML form, with an upload field:
 Example
 This code will produce an HTML form:
var http = require('http');

http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/html'});
  res.write('<form action="fileupload" method="post" enctype="multipart/form-data">');
  res.write('<input type="file" name="filetoupload"><br>');
  res.write('<input type="submit">');
  res.write('</form>');
  return res.end();
}).listen(8080);
Upload Files cont’d
Step 2: Parse the Uploaded File
Include the Formidable module to be able to parse the uploaded file once it reaches the server.
When the file is uploaded and parsed, it gets placed on a temporary folder on your computer.
Example
The file will be uploaded, and placed on a temporary folder:
var http = require('http');
var formidable = require('formidable');

http.createServer(function (req, res) {
  if (req.url == '/fileupload') {
    var form = new formidable.IncomingForm();
    form.parse(req, function (err, fields, files) {
      res.write('File uploaded');
      res.end();
    });
  } else {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.write('<form action="fileupload" method="post" enctype="multipart/form-data">');
    res.write('<input type="file" name="filetoupload"><br>');
    res.write('<input type="submit">');
    res.write('</form>');
    return res.end();
 }
}).listen(8080);
Upload Files cont’d
Step 3: Save the File
 When a file is successfully uploaded to the server, it is placed on a temporary folder.
 The path to this directory can be found in the "files" object, passed as the third argument in
the parse() method's callback function.
 To move the file to the folder of your choice, use the File System module, and rename the file:
 Example
 Include the fs module, and move the file to the current folder:
var http = require('http');
var formidable = require('formidable');
var fs = require('fs');
http.createServer(function (req, res) {
  if (req.url == '/fileupload') {
    var form = new formidable.IncomingForm();
    form.parse(req, function (err, fields, files) {
      var oldpath = files.filetoupload.path;
      var newpath = 'C:/Users/Your Name/' + files.filetoupload.name;
      fs.rename(oldpath, newpath, function (err) {
        if (err) throw err;
        res.write('File uploaded and moved!');
        res.end();
      });
 });}else { //form creation code } }).listen(8080);
Node.js URL Module
 The Built-in URL Module
 The URL module splits up a web address into readable parts.
 To include the URL module, use the 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:
 Example
 Split a web address into readable parts:
var url = require('url');
var adr = 'http://localhost:8080/default.htm?year=2017&month=february';
var q = url.parse(adr, true);

console.log(q.host); //returns 'localhost:8080'
console.log(q.pathname); //returns '/default.htm'
console.log(q.search); //returns '?year=2017&month=february'

var qdata = q.query; //returns an object: { year: 2017, month: 'february' }


console.log(qdata.month); //returns 'february'
Node.js File Server
 Now we know how to parse the query string, and in the previous chapter we
learned how to make Node.js behave as a file server.
 Let us combine the two, and serve the file requested by the client.
 Create two html files and save them in the same folder as your node.js files.
 summer.html
<!DOCTYPE html>
<html>
<body>
<h1>Summer</h1>
<p>I love the sun!</p>
</body>
</html>
 winter.html
<!DOCTYPE html>
<html>
<body>
<h1>Winter</h1>
<p>I love the snow!</p>
</body>
</html>
Node.js File Server cont’d
 Create a Node.js file that opens the requested file and returns the content to the client. If
anything goes wrong, throw a 404 error:
 demo_fileserver.js:
var http = require('http');
var url = require('url');
var fs = require('fs');

http.createServer(function (req, res) {
  var q = url.parse(req.url, true);
  var filename = "." + q.pathname;
  fs.readFile(filename, function(err, data) {
    if (err) {
      res.writeHead(404, {'Content-Type': 'text/html'});
      return res.end("404 Not Found");
    } 
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.write(data);
    return res.end();
  });
}).listen(8080);
Node.js File Server cont’d
 Remember to initiate the file:
 Initiate demo_fileserver.js:
 C:\Users\Your Name>node demo_fileserver.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.html
 Will produce this result:
 Summer
 I love the sun!
 http://localhost:8080/winter.html
 Will produce this result:
 Winter
 I love the snow!
Node.js Send an Email
The Nodemailer Module
 The Nodemailer module makes it easy to send emails
from your computer.
 The Nodemailer module can be downloaded and installed
using npm:
 C:\Users\Your Name>npm install nodemailer
 After you have downloaded the Nodemailer module, you
can include the module in any application:
 var nodemailer = require('nodemailer');
Send an Email
Example
var nodemailer = require('nodemailer');
var transporter = nodemailer.createTransport({
  service: 'gmail',
  auth: {
    user: 'youremail@gmail.com',
    pass: 'yourpassword'
 }
});
var mailOptions = {
  from: 'youremail@gmail.com',
  to: 'myfriend@yahoo.com',
  subject: 'Sending Email using Node.js',
  text: 'That was easy!'
};
transporter.sendMail(mailOptions, function(error, info){
  if (error) {
    console.log(error);
  } else {
    console.log('Email sent: ' + info.response);
 }
});
Multiple Receivers
 To send an email to more than one receiver, add them to
the "to" property of the mailOptions object, separated by
commas:
 Example
 Send email to more than one address:
 var mailOptions = {
  from: 'youremail@gmail.com',
  to: 'myfriend@yahoo.com, myotherfriend@yahoo.com',
  subject: 'Sending Email using Node.js',
  text: 'That was easy!'
}
Send HTML
 To send HTML formatted text in your email, use the
"html" property instead of the "text" property:
 Example
 Send email containing HTML:

var mailOptions = {
  from: 'youremail@gmail.com',
  to: 'myfriend@yahoo.com',
  subject: 'Sending Email using Node.js',
  html: '<h1>Welcome</h1><p>That was easy!</p>'
}
Node.js Events
Node.js is perfect for event-driven applications.
 Events in Node.js
 Every action on a computer is an event. Like when a connection
is made or a file is opened.
 Objects in Node.js can fire events, like the readStream object
fires events when opening and closing a file:
 Example
var fs = require('fs');
var rs = fs.createReadStream('./demofile.txt');
rs.on('open', function () {
  console.log('The file is open');
});
Events Module
 Node.js has a built-in module, called "Events", where you
can create-, fire-, and listen for- your own events.
 To include the built-in Events module use
the 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();
The EventEmitter Object
 You can assign event handlers to your own events with the EventEmitter object.
 In the example below we have created a function that will be executed when a
"scream" event is fired.
 To fire an event, use the emit() method.
 Example
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');
References
 https://www.nodebeginner.org
 https://www.w3schools.com/nodejs/nodejs_filesystem.asp
 https://www.w3schools.com/nodejs/nodejs_url.asp
 https://www.w3schools.com/nodejs/nodejs_npm.asp
 https://www.w3schools.com/nodejs/nodejs_events.asp
Any Query

You might also like