Njs Flashcards

1
Q

How do you start to create a program in nodeJs?

A

npm init

npm init -y

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

How do u install a package in nodeJS?

A

npm install ws

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How do u run a nodeJS program?

A

node index.js

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is “g” in,

npm install -g

A

It installs a package in a globally available system directory. You can find that directory with following command,
npm root -g

It won’t install it in the current project directory. That has to be done again without “-g”.
After this you can install this package even if internet is not available. It will install the package from local system directory.

You may need root access.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Give an example of importing a package in nodeJS.

A

const WebSocket = require(‘ws’);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

How do you printf from a NodeJs program?

A

console.log(“Hello World”);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

How do you catch an event in Node.js

A

using “on” method of EventEmitter.

eventEmitter.on(“evnt_name”, handlerFunctionName);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

How do u read a file in nodeJs?

A
var fs = require('fs');
fs.readFileSync("./filename.txt");
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What is a good for NodeJs documentation.

A

www.nodejs.org/api
or
www.nodejs.org -> go to ‘Docs’ tab.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

what are var, const and let variables in Node.js

A

var declares a variable.
const declares and defines a variable, that cannot be re-assigned.

let x = 5 defines a variable only at the block level, like a for loop counter etc.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Where to look for node.js packages

A

www.npmjs.com

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

How are constructor defined in nodejs class?

A
Inside class curly brackets,
constructor(firstName, LastName) { ... }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

How do you drive a child class from parent class in node.js?

A

class child_class extends parent_class { … }

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

How do u call constructor of parent class in child class in node.js?

A

super( parent class parameters);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

How is event emitted in node.js?

A

eventEmitter.emit(‘event_name’); // No event parameters
Handle with the function like this,
function event_handler() { … }
Bind event_name and event_handler() as follows,
eventEmitter.on(‘event_name’, event_handler);

If event has parameters, event_handler function should also accept same parameters, see below,

eventEmitter.emit(‘event_name’, event_arg1, event_arg2);
event_handler(event_arg1, event_arg2) { … }

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

How is event emitter is created in node.js?

A
var events = require('events');
var eventEmitter = nre events.EventEmitter();
eventEmitter.on('event_name', function_name);
eventEmitter.emit('event_name', arg1, arg2);
function function_name(arg1, arg2) { ... }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

How is util package used to make a child_class inherit a parent_class in node.js?

A
var util = require('util');
util.inherits(child_class, parent_class);
This can be used to make a class event emitter
var events = require('events');
util.inherits(child_class, events.EventEmitter);
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

How to add time delay in a NodeJs program?

A
npm install sleep
var sleep = require("sleep");
sleep.sleep(5);  // 5 second delay
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

How do u access command line args in node.js

A

process.argv
This will return an array
process variable is available to all node.js programs.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

How do you access process details in a node.js program

A

By using “process” variable available to all node.js programs
process.stdout.write(“Hello\n”);
is same as console.log(“hello”);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

In node.js how to call a function 5 seconds from now?

A
function func1() {...}
setTimeout(func1, 5000)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

In node.js, How to call a function repeatedly every 3 seconds?

A

setInterval(func1, 3000);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

How to exit a node.js program at any place in code?

A

process.exit();

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

In node.js, what package is needed to create a UDP socket?

A
const dgram = require('dgram');
const client_skt = dgram.createSocket('udp4');
const srvr_skt = dgram.createSocket('udp4');
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

How to create a buffer from a string in node.js?

A

var buf = new Buffer.from(“ABCD”);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

How to create a buffer of a specified length in node.js?

A

var buf = Buffer.alloc(15);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

How do u write a string to a buffer in node.js?

A
var bfr = Buffer.alloc(256);
len = bfr.write("ABCD");
len is octets written.
28
Q

Give example of a map in node.js

A

var sqrs = new Map([ [7, 49], [8, 64], [9, 81] ]);

29
Q

In node.js, how to read a file line by line?

A
use package line-by-line.
const  lineReader = require('line-by-line');
lr = lineReader('file_name.txt');
lr.on('line', function(txt) {// txt is a full line});
lr.on('end', function(){// end of file reached});
lr.on('error', function(err){print err});
30
Q

In node.js, how to call functions defined in another js file?

A
// math.js
function add(x, y) {return x+y;}
function mult(x, y) { return x*y;}
module.exports = {add, mult};
// app.js
var hisaab = require('./math');
m = hisaab.mult(7, 8);
s = hisaab.add(5, 7);
31
Q

Give an example of class definition in node.js

A
class Person{
  constructor(nm){
    this.name = nm;
  }
  printName() {
    console.log(this.name);
  }
}
john = new Person('John Doe');
john.printName();
32
Q

How to find 3rd character in a string name?

A

name = “Elon”;

console.log(name.charAt(2)); // prints o

33
Q

How to convert an integer to ascii string in node.js?

A
var num = 217;
var str_rep = num.toString();
console.log(typeof  str_rep);  // prints string
34
Q

How to find the type of an object in node.js?

A
var age = 29;
console.log(typeof age);  // prints number
var name = "Spock";
console.log(typeof name); // prints string
35
Q

How to concatenate two strings in node.js?

A
var firstName = "Elon";
var lastName = "  Musk";
var fullName = firstName.concat(lastName);
36
Q

How to declare an arry in node.js?

A
var names = [];
var cities = ["Delhi", "Washington"];
citiess.push("London");
37
Q

What are node.js objects?

A

key: value pairs,
value can be a function

var Person = {
  firstName : "Isac",
  lastName : " Newton",
  fullName : function {
   fn = this.firstName.concatenate(this.lastName);
    return fn;
  }
}
38
Q

How to find length of an array in node.js?

A
var sqr = [1, 4, 9, 16]
sqr.length;
39
Q

How to iterate over an array in node.js?

A
var arr = [1, 2, 3];
for(let i in arr){
  console.log(arr[i]);
}
40
Q

In node.js, how do you convert an string to a JSON object?

A
var str = "{\"age\": 47}";
var jsnObj = JSON.parse(str);
To convert JSON obect to string
var str2 = JSON.stringify(jsnObj);

To get length of a JSON array
jsnObj.length;

41
Q

In node.js, how do u split a string?

A

use string.split(“ “);
str = “aaaaKKbbbbKK123”;
str.split(“KK”); // [“aaaa”, “bbbb”, “123”]

To split a multi-line string into separate lines,
os = require(‘os’);
str = fs.readFileSync(‘file_1.txt’).toString();
lines = str.split(os.EOL);

42
Q

In node.js, how to separate a file content into individual lines synchronously?

A
os = require('os');
str = fs.readFileSync('file_1.txt').toString();
lines = str.split(os.EOL);
43
Q

How do you get the request type (GET, POST) from a HTTP type in node.js? Also how to retrive POSTed data at the server?

A

In request handler function, there are two parameters (req, resp). Request type is available in req.method (GET or POST).

44
Q

How to install nodejs on Ubuntu?

A

For latest procedure, got to www.nodejs.org
–> Downloads –> Debian & Ubuntu …

This directs to github
https://github.com/nodesource/distributions/blob/master/README.md#deb

For version 10.x procedure is,

curl -sL https://deb.nodesource.com/setup_10.x | sudo -E bash -
sudo apt-get install -y nodejs

45
Q

How to update npm to latest version in nodejs?

A

sudo npm install -g npm

46
Q

nodejs: How to list globally installed packages?

A

npm list -g

npm list -g –depth=0

47
Q

nodejs: How to un-install a package?

A

npm uninstall pkg_name

48
Q

nodejs: How to search list of available packages containing a given string?

A

npm search mkdir

mkdir is string to search in package names.

49
Q

nodejs: How to create a file synchronously, and write to it?

A
var  fd = fs.openSync("./new_file.txt", "w");
fs.writeSync(fd, "ABCDWXYZ", 0, 9, null);
50
Q

nodejs: How to get string representation of an integer?

A
var num = 123;
var str = num.toString();
51
Q

nodejs: How to filter out negative numbers from an array?

A
function isPositive(num) { return num > 0; }
arr = [15, 7, -65, 9, -25];
newArr = arr.filter(isPositive);
52
Q

nodejs: How to remove first element of an array?

A

use shift()
let cats = [‘Bob’, ‘Willy’, ‘Mini’];
cats.shift(); // [‘Willy’, ‘Mini’]

shift() returns the removed item.

To remove last, item use pop()

53
Q

nodejs: How to check if an array is empty?

A

if(arr.length > 0) { // Array is not empty }

54
Q

Nodejs: How to find all keys in a json object?

A
const  jsnStr = "{ ....... }";
var jsnObj = JSON.parse(jsnStr);
var keys = Object.keys(jsnObj);

variable keys will contain an array of all key strings.

55
Q

Nodejs: What is “Object”?

A

It is some kind of a global object, available everywhere. It has many useful functions built into it, e.g.,
Object.keys()
can be used to find all keys in a json object.
Find out more about it.

56
Q

Nodejs: How to find length of a string?

A
const str = "ABCDEF";
var len = str.length;
57
Q

Nodejs: what exactly is the difference between __proto__ and prototype?

A

Find out more about it.

58
Q

Nodejs: how do u throw an exception?

A
Try {
  throw new Error('error msg');
}
catch(e) {
  console.log(e.message);
}
finally {
  // this will always execute
}
59
Q

Nodejs: How to print variables in a string?

A
let  var1 = 123;
console.log(`Value of var1 is  ${var1}`);
Note we have used back ticks on left of '1' key.
60
Q

Nodejs: what does Object.create() do?

A

When u create a new object from an existing one using Object.create(), the new object looks for properties in parent object if it fails to find them in itself.

childObj = Object.create(parentObj);
childObj.prop_A;
if prop_A is not there in childObj, it will be looked in parent.

61
Q

Nodejs: How are global variables implemented internally in NodeJs?

A

There is a “Global Object”, all global variables are properties or attributes of this object.

62
Q

Nodejs: How are local variables implemented internally in NodeJs?

A

Each time a function is called, a “Call Object” is created. Each local variable in that function is attribute or property of that “Call Object”.

When using a variable, most recent “Call Object” is searched first for that variable. If this search fails, next most recent “Call Object” is searched, all the way up to “Global Object”.

63
Q

NodeJs: How can you modify some characters in a string?

A

You can’t really modify a string. They are immutable.

64
Q

NodeJs: What is ‘delete’ used for?

A

delete is used to remove individual attributes/properties of objects. Not whole objects, which is automatically done by the garbage collector.

65
Q

NodeJs: What is ‘arguments’ object?

A

Inside a function, arguments object is an array, that contains all arguments passed to that function invocation, even if number of arguments defined is less then called actual arguments.

arguments.length is the total number of arguments passed to this function invocation.