Node.js Notes
# Node.js - Node.js capabilities: - File system - URL Module - Events - Upload files - Introduction to the Express framework - Server-side rendering with Templating Engines - Static Files - async/await - Fetching JSON from Express. # File System Module - Allows interaction with the computer's file system. - Include the module using the `require()` method: - - Common uses: - Read files - Create files - Update files - Delete files - Rename files ## Read Files - The `fs.readFile()` method is used to read files. - Example: - Assume `demofile1.html` exists: ```html
My Header
My paragraph.
``` - Node.js code to read and return the HTML file content: ```javascript 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); return res.end(); }); }).listen(8080); ``` - To initiate the file: - ```bash C:\Users\Your Name>node demo_readfile.js ``` ## Create Files - Methods for creating files: - `fs.appendFile()` - `fs.open()` - `fs.writeFile()` ### `fs.appendFile()` - Appends content to a file; creates the file if it doesn't exist. - Example: ```javascript var fs = require('fs'); fs.appendFile('mynewfile1.txt', 'Hello content!', function (err) { if (err) throw err; console.log('Saved!'); }); ``` ### `fs.open()` - Opens a file with a specified flag. If the flag is 'w' (writing) and the file doesn't exist, an empty file is created. - Example: ```javascript var fs = require('fs'); fs.open('mynewfile2.txt', 'w', function (err, file) { if (err) throw err; console.log('Saved!'); }); ``` ### `fs.writeFile()` - Replaces the file and its content if the file exists. Creates a new file if it doesn't exist. - Example: ```javascript var fs = require('fs'); fs.writeFile('mynewfile3.txt', 'Hello content!', function (err) { if (err) throw err; console.log('Saved!'); }); ``` ## Update Files - Methods for updating files: - `fs.appendFile()` - `fs.writeFile()` ### `fs.appendFile()` (for updating) - Appends content to the end of the file. - Example: ```javascript var fs = require('fs'); fs.appendFile('mynewfile1.txt', ' This is my text.', function (err) { if (err) throw err; console.log('Updated!'); }); ``` ### `fs.writeFile()` (for updating) - Replaces the content of the file. - Example: ```javascript var fs = require('fs'); fs.writeFile('mynewfile3.txt', 'This is my text', function (err) { if (err) throw err; console.log('Replaced!'); }); ``` ## Delete Files - The `fs.unlink()` method deletes the specified file. - Example: ```javascript var fs = require('fs'); fs.unlink('mynewfile2.txt', function (err) { if (err) throw err; console.log('File deleted!'); }); ``` ## Rename Files - The `fs.rename()` method renames the specified file. - Example: ```javascript var fs = require('fs'); fs.rename('mynewfile1.txt', 'myrenamedfile.txt', function (err) { if (err) throw err; console.log('File Renamed!'); }); ``` # Formidable Module - Used for handling file uploads. - Installation via NPM: - ```bash C:\Users\Your Name>npm install formidable ``` - Include the module: - ## Upload Files - Steps ### Step 1: Create an Upload Form - Create an HTML form with an upload field. - Example: ```javascript var http = require('http'); http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/html'}); res.write('
'); res.write('
'); res.write(''); res.write('
'); return res.end(); }).listen(8080); ``` ### Step 2: Parse the Uploaded File - Use the Formidable module to parse the uploaded file. - The file is placed in a temporary folder on the computer. - Example: ```javascript 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('
'); res.write('
'); res.write(''); res.write('
'); return res.end(); } }).listen(8080); ``` ### Step 3: Save the File - Move the file from the temporary folder to the desired location using the File System module. - Example: ```javascript 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.filepath; var newpath = 'C:/Users/Your Name/' + files.filetoupload.originalFilename; fs.rename(oldpath, newpath, function (err) { if (err) throw err; res.write('File uploaded and moved!'); res.end(); }); }); } else { res.writeHead(200, {'Content-Type': 'text/html'}); res.write('
'); res.write('
'); res.write(''); res.write('
'); return res.end(); } }).listen(8080); ``` # URL Module - Splits a web address into readable parts. - Include the module: - - Parse an address with `url.parse()`: - Example: ```javascript 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' ``` - Combining URL and File System modules: - Example HTML files: - `summer.html`: ```html
Summer
I love the sun!
``` - `winter.html`: ```html
Winter
I love the snow!
``` - Node.js code to serve files based on the client's request: ```javascript 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); ``` - Initiate the file server: - ```bash C:\Users\Your Name>node demo_fileserver.js ``` - Results: - Accessing `http://localhost:8080/summer.html` will produce: ```html Summer I love the sun! ``` - Accessing `http://localhost:8080/winter.html` will produce: ```html Winter I love the snow! ``` # Events in Node.js - Node.js is suited for event-driven applications. - Every action on a computer is an event. - Objects in Node.js can fire events. - Example: `readStream` object fires events when opening and closing a file. - Example: ```javascript var fs = require('fs'); var rs = fs.createReadStream('./demofile.txt'); rs.on('open', function () { console.log('The file is open'); }); ``` ## Events Module - Built-in module for creating, firing, and listening for custom events. - Include the module: - - Event properties and methods are an instance of `EventEmitter`. - Create an `EventEmitter` object: - ## The EventEmitter Object - Assign event handlers to events using the `EventEmitter` object. - Fire an event using the `emit()` method. - Example: ```javascript 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'); ```