Nodejs
Nodejs
• A common task for a web server can be to open a file on the server
and return the content to the client. Here is how PHP or ASP handles
a file request:
• Sends the task to the computer's file system.
• Waits while the file system opens and reads the file.
• Returns the content to the client.
• Ready to handle the next request.
• how Node.js handles a file request:
• Sends the task to the computer's file system.
• Ready to handle the next request.
• When the file system has opened and read the file, the server returns the
content to the client.
• Node.js eliminates the waiting, and simply continues with the next
request.
• Node.js runs single-threaded, non-blocking, asynchronous
programming, which is very memory efficient.
Why node.js
• Parse an address with the url.parse() method, and it will return a URL
object with each part of the address as properties:
var url = require('url');
var adr = 'http://localhost:8080/default.htm?year=2017&month=february';
var q = url.parse(adr, true);
• 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: Open the command line interface and use NPM
to download the package you want.
“C:\Users\Your Name>npm install upper-case”
• 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.
C:\Users\My Name\node_modules\upper-case
Using a Package
• 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:
var http = require('http'); } else {
var formidable = require('formidable');
res.writeHead(200, {'Content-Type':
var fs = require('fs');
'text/html'});
http.createServer(function (req, res) { res.write('<form
if (req.url == '/fileupload') { action="fileupload" method="post"
var form = new formidable.IncomingForm(); enctype="multipart/form-data">');
form.parse(req, function (err, fields, files) { res.write('<input type="file"
var oldpath = files.filetoupload.filepath; name="filetoupload"><br>');
var newpath = 'C:/Users/Your Name/' + res.write('<input type="submit">');
files.filetoupload.originalFilename;
fs.rename(oldpath, newpath, function (err) { res.write('</form>');
if (err) throw err; return res.end();
res.write('File uploaded and moved!');
}
res.end();
}); }).listen(8080);
});