Summary

This document provides a comprehensive overview of Node.js, a server-side runtime environment based on Google Chrome's JavaScript Engine. It explains its functionalities, usage in web development, and various aspects.

Full Transcript

Node.js Node.js is a server-side runtime environment built on Google Chrome's JavaScript Engine (V8 Engine). Node.js is not a programming language like Python, Java or C/C++. Node.js is a cross-platform (run on Windows, Linux, Unix, macOS, and more), open- source, back-end JavaScript r...

Node.js Node.js is a server-side runtime environment built on Google Chrome's JavaScript Engine (V8 Engine). Node.js is not a programming language like Python, Java or C/C++. Node.js is a cross-platform (run on Windows, Linux, Unix, macOS, and more), open- source, back-end JavaScript runtime environment, that executes JavaScript code outside a web browser. Node.js is a runtime, similar to Java virtual machine, that converts JavaScript code into machine code. It is , widely used by thousands of developers around the world to develop I/O intensive web applications like video streaming sites, single- page applications, and other web applications. With Node.js, it is possible to use JavaScript as a backend. Node.js is used for server-side programming with JavaScript. Hence, you can use a single programming language (JavaScript) for both front-end and back-end development. Node.js implements asynchronous execution of tasks in a single thread with async and await technique. This makes Node.js application significantly faster than multi-threaded applications. Node.js is being used to build command line applications, web applications, real-time chat applications, REST APIs etc. Install Node.js on Windows To install and setup an environment for Node.js, you need the following two software's available on your computer: Text Editor. Node.js Binary installable The source files for Node.js programs are typically named with the extension ".js". To download Node.js https://nodejs.org/en/ The source code written in source file is simply JavaScript. It is interpreted and executed by the Node.js interpreter. Node.js First Example Create file name with example1.js console.log('Hello World'); Open Node.js command prompt and run the following code: node example1.js A node.js web application contains the following three parts: 1. Import required modules: The "require" directive is used to load a Node.js module. 2. Create server: You have to establish a server which will listen to client's request similar to Apache HTTP Server. 3. Read request and return response: Server created in the second step will read HTTP request made by client which can be a browser or console and return the response. Steps to create node.js web applications 1. use require() directive to load http module and store returned HTTP instance into http variable. For example: var http = require("http"); 2. i)call http.createServer() ii) bind at port 8081 using listen method associated with server instance. iii)Pass it a function with request and response parameters and write the sample implementation to return "Hello World". http.createServer(function (request, response) { // Send the HTTP header // HTTP Status: 200 : OK // Content Type: text/plain response.writeHead(200, {'Content-Type': 'text/plain'}); // Send the response body as "Hello World" response.end('Hello World\n'); }).listen(8081); // Console will print the message console.log('Server running at http://127.0.0.1:8081/'); 3. Combine step1 and step2 together in a file named “console.js“. To Start server Console The Node.js console module provides a simple debugging console similar to JavaScript console mechanism provided by web browsers. There are three console methods that are used to write any node.js stream: a. console.log() b. console.error() c. console.warn() console.log() The console.log() function is used to display simple message on console. Example:console.log(‘DEMO'); console.error() The console.error() function is used to render error message on console. Ex: console.error(new Error('Hell! This is a wrong method.')); console.warn() Ex: const name = 'John'; console.warn(`Don't mess with me $ {name}! Don't mess with me!`); REPL REPL stands for Read Eval Print and Loop. It specifies a computer environment like a window console or a Unix/Linux shell where you can enter the commands and the system responds with an output in an interactive mode. The Node.js or node come bundled with REPL environment. Each part of the REPL environment has a specific work. i. Read: It reads user's input; parse the input into JavaScript data-structure and stores in memory. ii. Eval: It takes and evaluates the data structure. iii. Print: It prints the result. iv. Loop: It loops the above command until user press ctrl-c twice. REPL(Continued..) You can start REPL by simply running "node" on the command prompt. After starting REPL node command prompt put any mathematical expression: Ex: > 12*3 36 variable Variables are used to store values and print later. Multiline expressions underscore _ You can also use underscore _ to get the last result. Use ctrl + c command twice to come out of Node.js REPL Node.js REPL Commands Node.js Package Manager(npm) Node Package Manager provides two main functionalities: 1. It provides online repositories for node.js packages/modules which are searchable on search.nodejs.org 2. It also provides command line utility to install Node.js packages, do version management and dependency management of Node.js packages. The npm comes bundled with Node.js installables in versions after that v0.6.3. To check the version by opening Node.js command prompt and typing the following command: npm version Installing Modules using npm The syntax to install any Node.js module: npm install To install a famous Node.js web framework called express npm install express To use this module in js file var express = require('express'); By default, npm installs dependency in local mode. Here local mode specifies the folder where Node application is present. For example if you installed express module, it created node_modules directory in the current directory where it installed express module. Global vs Local Installation To list down all the locally installed modules: npm ls Globally installed packages/dependencies are stored in system directory. Let's install express module using global installation. Although it will also produce the same result but modules will be installed globally. npm install express -g To uninstall a Node.js module, use the following command: npm uninstall express You can verify by using the following command: npm ls Node.js Command Line Options The following are the list of Node.js command line options: Option Description v, --version It is used to print node's version. -h, --help It is used to print node command line options. -e, --eval "script" It evaluates the following argument as JavaScript. The modules which are predefined in the REPL can also be used in script. -p, --print "script" It is identical to -e but prints the result. -c, --check Syntax check the script without executing. -i, --interactive It opens the REPL even if stdin does not appear to be a terminal. Node.js Global Objects Node.js global objects are global in nature and available in all modules. You don't need to include these objects in your application; rather they can be used directly. These objects are modules, functions, strings and object etc. A list of Node.js global objects are given below: __dirname __filename Console Process Buffer setImmediate(callback[, arg][,...]) setInterval(callback, delay[, arg][,...]) setTimeout(callback, delay[, arg][,...]) clearImmediate(immediateObject) clearInterval(intervalObject) clearTimeout(timeoutObject) Node.js Global Objects(Cont..) Node.js __dirname It specifies the name of the directory that currently contains the code. console.log(__dirname); Node.js __filename It specifies the filename of the code being executed. console.log(__filename); Node.js Errors The Node.js applications generally face four types of errors: 1. Standard JavaScript errors i.e. , , , , , etc. 2. System errors :These errors occur when Node.js encounters an underlying system- related issue, such as file access, network failure, or hardware problems. 3. User-specified errors: These errors are manually created by developers, usually to indicate a specific problem in the application logic 4. Assertion errors: Assertion errors occur when a condition in your code fails. Example for standard JavaScript error - Reference Error. // Throws with a ReferenceError because b is undefined try { const a = 1; const c = a + b; } catch (err) { console.log(err); } Node.js Streams Streams are the objects that facilitate you to read data from a source and write data to a destination. There are four types of streams in Node.js: 1. Readable: This stream is used for read operations. 2. Writable: This stream is used for write operations. 3. Duplex: This stream can be used for both read and write operations. 4. Transform: It is type of duplex stream where the output is computed according to input. Following are some commonly used events: 1. Data: This event is fired when there is data available to read. 2. End: This event is fired when there is no more data available to read. 3. Error: This event is fired when there is any error receiving or writing data. 4. Finish: This event is fired when all data has been flushed to underlying system. Node.js Reading from stream Step1:Create a text file and add some information to the text file. Step2:Create a JavaScript file having the following code: var fs = require("fs"); var data = ''; // Create a readable stream var readerStream = fs.createReadStream('input.txt'); // Set the encoding to be utf8. readerStream.setEncoding('UTF8'); // Handle stream events --> data, end, and error readerStream.on('data', function(chunk) { data += chunk; }); readerStream.on('end',function(){ console.log(data); }); readerStream.on('error', function(err){ console.log(err.stack); }); console.log("Program Ended"); Node.js Writing to stream Create a Javascript file with the following code: var fs = require("fs"); var data = 'A Solution of all Technology'; // Create a writable stream var writerStream = fs.createWriteStream('output.txt'); // Write the data to stream with encoding to be utf8 writerStream.write(data,'UTF8'); // Mark the end of file writerStream.end(); // Handle stream events --> finish, and error writerStream.on('finish', function() { console.log("Write completed."); }); writerStream.on('error', function(err){ console.log(err.stack); }); console.log("Program Ended"); Node.js Piping Streams Piping is a mechanism where output of one stream is used as input to another stream. Example: Program for reading from one file and writing it to another file. var fs = require("fs"); // Create a readable stream var readerStream = fs.createReadStream('input.txt'); // Create a writable stream var writerStream = fs.createWriteStream('output.txt'); // Pipe the read and write operations // read input.txt and write data to output.txt readerStream.pipe(writerStream); console.log("Program Ended"); Callbacks Programming instructions are executed synchronously by default. If one of the instructions in a program is expected to perform a lengthy process, the main thread of execution gets blocked. The subsequent instructions can be executed only after the current I/O is complete. This is where callbacks come in to the picture. A Callback in Node.js is an asynchronous equivalent for a function. It is a special type of function passed as an argument to another function. It help us make asynchronous calls. The callback is called when the function that contains the callback as an argument completes its execution and allows the code in the callback to run in the meantime. It can process a high number of requests without waiting for any function to return results. Callbacks(Cont..) The syntax of implementing callback in Node.js is as follows − function function_name(argument, function (callback_argument) { // callback body }) setTimeout() function in Node.js is a typical example of callback. The following code calls the asynchronous setTimeout() method, which waits for 1000 milliseconds, but doesn't block the thread. Instead, the subsequent Hello World message, followed by the timed message. setTimeout(function () { console.log('This prints after 1000 ms‘ ); }, 1000); console.log("Hello World"); Callbacks(Cont..) Blocking Code The following code reads the file synchronously with the help of readFileSync() function in fs module. Since the operation is synchronous, it blocks the execution of the rest of the code. var fs = require("fs"); var data = fs.readFileSync('input.txt'); console.log(data.toString()); let i = 1; while (i

Use Quizgecko on...
Browser
Browser