Posts

Showing posts from October, 2020

What is promise, promise.all and promise.race? How do you chain promises?

A promise is an object that may produce a single value some time in the future : either a resolved value, or a reason that it’s not resolved (e.g., a network error occurred). A promise is an object which can be returned synchronously from an asynchronous function. It will be in one of 3 possible states: Fulfilled:   onFulfilled()  will be called (e.g.,  resolve()  was called) Rejected:   onRejected()  will be called (e.g.,  reject()  was called) Pending:  not yet fulfilled or rejected A promise is  settled  if it’s not pending (it has been resolved or rejected). Sometimes people use  resolved  and  settled  to mean the same thing:  not pending . Once settled, a promise can not be resettled. Calling  resolve()  or  reject()  again will have no effect. The immutability of a settled promise is an important feature. Promises following the spec must follow a specific set of rules: A promise or...

How do you create a hello world Node JS application

npm init npm install express --save var express = require('express'); var app = express(); app.get('/', function (req, res) { res.send('Hello World!'); }); app.listen(3000, function () { console.log('Example app listening on port 3000!'); }); node app.js

What are clusters and worker threads, and when would you use them?

Worker threads are for when you want to run long-running synchronous tasks, and you don't want to block the event loop. It runs the code in a separate thread, and can communicate the results back to the main thread. Cluster workers are separate instances of your Node process, which are primarily used for load balancing incoming requests across multiple processes, to take advantage of multi-core processors.

What is V8 Engine? What is the relationship between Node.js and V8?

  V8 Engine is Google’s open source javascript and written in C++ and used inside Google Chrome. It was designed for increasing the performance of JavaScript execution inside web browsers. V8 is the Javascript engine inside of node.js that parses and runs your Javascript. The same V8 engine is used inside of Chrome to run javascript in the Chrome browser. Google open-sourced the V8 engine and the builders of node.js used it to run Javascript in node.js.

How to make Post request in Node.js?

  var request = require('request'); request.post(      'http://www.example.com/action',      { form: { key: 'value' } },      function (error, response, body) {           if (!error && response.statusCode == 200) {                console.log(body)           }      } );

What is the command used to import external libraries?

  The “ require ” command is used for importing external libraries.  Example: var http=require (“http”) It will load the http library . The single exported object through the http variable.

What is the difference between fork() and spawn() methods in Node.js?

  fork() spawn() fork() is a particular case of spawn() that generates a new instance of a V8 engine. Spawn() launches a new process with the available set of commands. Multiple workers run on a single node code base for multiple tasks. This method doesn’t generate a new V8 instance and only a single copy of the node module is active on the processor.

What is piping and chaining in Node.js?

Piping the Streams Piping is a mechanism where we provide the output of one stream as the input to another stream . It is normally used to get data from one stream and to pass the output of that stream to another stream. There is no limit on piping operations. Now we'll show a piping example for reading from one file and writing it to another file. Create a js file named main.js with the following code − 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" ); Now run the main.js to see the result − $ node main.js Verify the Output. Program Ended Open output.txt created in your current directory; it should contain the following − Tu...

What is a reactor pattern in Node.js?

  A reactor pattern is a concept of non-blocking I/O operations. This pattern provides a handler that is associated with each I/O operation. As soon as an I/O request is generated, it is then submitted to a demultiplexer

What is an Event loop in Node.js and how does it work?

Image
  An event loop in Node.js handles all the asynchronous callbacks in an application .  It is one of the most important aspects of Node.js and the reason behind Node.js have non-blocking I/O. Since Node.js is an event-driven language, you can easily attach a listener to an event and then when the event occurs the callback will be executed by the specific listener. Whenever functions like setTimeout, http.get, and fs.readFile are called, Node.js executed the event loop and then proceeds with the further code without waiting for the output. Once the entire operation is finished, Node.js receives the output and then executes the callback function. This is why all the callback functions are placed in a queue in a loop. Once the response is received, they are executed one by one.

Why do you use forever with Node.js ?

  forever   is a node.js package that is used to keep the server alive even when the server crash/stops. When the node server is stopped because of some error, exception, etc. forever automatically restarts it. Forever can be used as forever start app.js Finally, the purpose of  forever  is to keep a child process (such as our node.js web server) running continuously and automatically restart it when it exits unexpectedly.  forever  has some default options and configuration convention as follow: forever  keeps track of running processes in  *.fvr  files that are placed in  /tmp/forever/pids Each  forever  process will generate a unique log file placed in  /tmp/forever/*.log Unless otherwise specified, the output of the child process'  stdout  and  stderr  will be written to the above log file.

What is Buffer in Node.js?

  Buffers are instances of the   Buffer   class in node, which is designed to handle raw binary data. Each buffer corresponds to some raw memory allocated outside V8. Buffers act somewhat like arrays of integers, but aren't resizable and have a whole bunch of methods specifically for binary data. Pure JavaScript does not handle straight binary data very well. This is fine on the browser, where most data is in the form of strings. However, Node.js servers have to also deal with TCP streams and reading and writing to the filesystem, both which make it necessary to deal with purely binary streams of data. Below are the ways to create new buffers: var bufferOne = new Buffer( 8 ); // Uninitalized buffer and contains 8 bytes var bufferTwo = new Buffer([ 8 , 6 , 7 ]); //This initializes the buffer to the contents of this array. The array are integers representing bytes. var bufferThree = new Buffer( "This is a string" , "utf-8" ) // This initializes the bu...

What is zlib? How do you compress a file in Node.js?

  The   zlib   module provides compression functionality implemented using Gzip and Deflate/Inflate. var zlib = require ( 'zlib' ); var gzip = zlib.createGzip(); var fs = require ( 'fs' ); var inp = fs.createReadStream( 'input.txt' ); var out = fs.createWriteStream( 'input.txt.gz' ); inp.pipe(gzip).pipe(out); Calling  .flush()  on a compression stream will make  zlib  return as much output as currently possible. This may come at the cost of degraded compression quality, but can be useful when data needs to be available as soon as possible.

What are Global objects in Node.js?

  Node.js has some Global objects which are available in all modules. Some of these objects are not actually in global scope but in the module scope. __dirname : The directory name of the current module. This the same as the  path.dirname()  of the  __filename . __filename : The file name of the current module. This is the resolved absolute path of the current module file. exports : A reference to the  module.exports  that is shorter to type.  exports  is not actually a global but rather local to each module. require : To require modules.  require  is not actually a global but rather local to each module.

How to install a node module locally and globally? How to add them into package.json?

  By default, Node.js installs the module locally in the   ./node_modules   directory. To install a module globally and to make them available everywhere, we need to include the   -g   flag. npm install express -g To save the installed module to the  package.json  under  dependencies , add  --save  flag with the package name. To add under  deveDependencies  add  --save-dev .

How to support multi-processor platforms in Node.js

  Since Node.js is by default a single thread application, it will run on a single processor core and will not take full advantage of multiple core resources. However, Node.js provides support for deployment on multiple-core systems, to take greater advantage of the hardware.  The  Cluster  module is one of the core Node.js modules and it allows running multiple Node.js worker processes that will share the same port.

How can we avoid Callback Hell in Node.js?

Callback hell refers to heavily nested callbacks that have become unreadable and hard to debug. We can use   async   module. Async is a utility module which provides straight-forward, powerful functions for working with asynchronous JavaScript. Consider we have two functions which runs sequentially

What is Child Process and Cluster? What are the difference?

  Child Process   in Node.js is used to run a child process under Node.js. There are two methods to do that:   exec   and   spawn . The example for   exec   is: var exec = require ( 'child_process' ).exec; exec( 'node -v' , function ( error, stdout, stderr ) { console .log( 'stdout: ' + stdout); console .log( 'stderr: ' + stderr); if (error !== null ) { console .log( 'exec error: ' + error); } }); We are passing our command as our first argument of the  exec  and expect three response in the callback.  stdout  is the output we could expect from the execution. Cluster  is used to split a single process into multiple processes or  workers , in Node.js terminology. This can be achieved through a cluster module. The cluster module allows you to create child processes (workers), which share all the server ports with the main Node process (master). A cluster is a pool of similar workers running under a parent Node...

What is middlewares? What is the concept of middlewares in Express.js?

  Middleware functions are functions that have access to the request object ( req ), the response object ( res ), and the next middleware function in the application’s request-response cycle. The next middleware function is commonly denoted by a variable named next. Middleware functions can perform the following tasks: Execute any code. Make changes to the request and the response objects. End the request-response cycle. Call the next middleware function in the stack. Bind application-level middleware to an instance of the app object by using the  app.use()  and  app.METHOD()  functions, where  METHOD  is the HTTP method of the request that the middleware function handles (such as  GET ,  PUT , or  POST ) in lowercase. var app = express() app.use( function ( req, res, next ) { console .log( 'Time:' , Date .now()) next() })

How to test your code in Node.js?

  The   assert   module in Node.js provides easy way of writing test in a limited ways. It provides no feedback when running your tests unless one fails. It provides 11 methods to test our code to check it is working as we expect. Some of them are:   assert.equal ,   assert.deepEqual ,   assert.throws . assert.equal( 2 + 2 , 4 , 'two plus two is four' ); Other than this, we can use testing frameworks like,  mocha ,  chai  and  karma .