Sunday, September 18, 2016

Node basics

How to parse command line arguments in nodejs?

>node test.js hi hello cool

test,js
var cmdArgs = process.argv.slice(2);
console.log(cmdArgs); //prints ["hi","hello","cool"]

How to write a reusable module and how to import it in test.js?

myreusablemodule.js
module.exports = {
      sayHello : function(){
           console.log("Hello, how u doing?");
     }
};

test.js
var rModule = require("./myreusablemodule"); //returns whatever is assigned to module.exports
console.log(rModule.sayHello());

>node test.js

Explain about event driven programming in nodejs?

In an event driven programming, there is a main loop that listens for events, and then triggers a callback function when one of these events is detected.
Read more here: https://www.tutorialspoint.com/nodejs/nodejs_event_loop.htm

Give an example of event driven programming in nodejs?

All you need to remember is on and emit.

test.js
var events = require("events");
var eventsEmitter = new events.EventEmitter();
var mycustomeventassocfunction = function(){
      console.log("i am the response from mycustomeventassocfunction");
};
eventsEmitter.on("mycustomevent",mycustomeventassocfunction);

eventsEmitter.emit("mycustomevent");

>node test.js

How does the async functions work in nodejs?

Events and callbacks help nodejs to support concurrency.
database.query('something', function(err, result) {
  if (err) handle(err);
  doSomething(result);
});
The async function query takes callback function as the last parameter and the callback function takes err as the first parameter.
Read more here: https://www.tutorialspoint.com/nodejs/nodejs_event_loop.htm

What are the global objects in nodejs?

You don't have to require/include the global objects in nodejs programs. For example, console, process, __filename, __dirname, etc.

Read more here: https://www.tutorialspoint.com/nodejs/nodejs_global_objects.htm

test.js
console.log(__filename);

>node test.js

No comments:

Post a Comment