0% found this document useful (0 votes)
21 views9 pages

Node - Simple

Node is a JavaScript runtime that allows building fast and scalable network applications. It uses asynchronous and event-driven architecture making it ideal for I/O intensive applications. The document discusses Node core concepts like modules, events, streams and the HTTP module. It also covers using NPM to install packages and developing basic web servers.

Uploaded by

gepiged536
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views9 pages

Node - Simple

Node is a JavaScript runtime that allows building fast and scalable network applications. It uses asynchronous and event-driven architecture making it ideal for I/O intensive applications. The document discusses Node core concepts like modules, events, streams and the HTTP module. It also covers using NPM to install packages and developing basic web servers.

Uploaded by

gepiged536
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

THE COMPLETE NODE.

JS COURSE
GETTING STARTED:
- Node is a runtime environment for executing JS code

- Essentially, Node is a C++ program that embeds Chrome’s v8 engine, the fastest
JS engine in the world.

- We use Node to build fast and scalable networking applications. It’s a perfect
choice for building RESTful services.

- Node applications are single-threaded. That means a single thread is used to


serve all clients.

- Node applications are asynchronous or non-blocking by default. That means


when the application involves I/O operations (eg accessing the file system or the
network), the thread doesn’t wait (or block) for the result of the operation. It is
released to serve other clients.

- This architecture makes Node ideal for building I/O-intensive applications.

- You should avoid using Node for CPU-intensive applications, such as a video
encoding service. Because while executing these operations, other clients have
to wait for the single thread to finish its job and be ready to serve them.

- In Node, we don’t have browser environment objects such as window or the


document object. Instead, we have other objects that are not available in
browsers, such as objects for working with the file system, network, operating
system, etc.

FIRST PROGRAM:

function sayHello(name) {
console.log('hello' + name);
}
sayHello('ABD');
// node app.js – to run
// console.log(“this is node”);
// var message = ‘’;
// console.log(window.message) //error – window not defined; but works in browser
// console.log(global.message) //undefined – because message is not defined globally
// in browser env window and document will work but in node runtime env global will work
NODE CORE:
- We don’t have the window object in Node.
Ex:
// in browser env
console.log("abd") // => (internally) window.console.log("abd");

- The global object in Node is “global”.


Ex:
console.log("abd") // (internally) global.console.log("abd")

// shorthand - global methods

setTimeout()
clearTimeout()

setInterval()
clearInterval()

global.setTimeout // long way - we can access using global object

- Unlike browser applications, variables we define are not added to the “global” object.
Ex:
var message = '';
console.log(global.message); // undefined

- Every file in a Node application is a module. Node automatically wraps the code
in each file with an IIFE (Immediately-invoked Function Expression) to create
scope. So, variables and functions defined in one file are only scoped to that file
and not visible to other files unless explicitly exported.
console.log(module);
// module object not a global one so we cant access using global.module

- To export a variable or function from a module, you need to add them to


module.exports:
module.exports.sayHello = sayHello;
var url = "https://userlogger.co.in"

function replyBack (message) {


console.log("received " + message);
}
module.exports.replyBack = replyBack; // exporting using module
module.exports.webLink = url; // we can change name when exporting

- To load a module, use the require function. This function returns the
module.exports object exported from the target module:
const logger = require(‘./logger’);
const getLogger = require("./logger")
console.log(getLogger);

/* {
replyBack: [Function: replyBack],
webLink: 'https://userlogger.co.in'
} */
// logger.js
var url = "https://userlogger.co.in"

function replyBack (message) {


console.log("received " + message);
}

module.exports = replyBack; /// we set the export directly as function

// app.js

const getLogger = require("./logger")


getLogger('hello')

- Node has a few built-in modules that enable us to work with the file system, path
objects, network, operating system, etc.

To see modules and its methods go to node.js website > Docs

Path module
const path = require('path') // npm i path
const pathObj = path.parse( filename)
console.log(pathObj);
/* output
{
root: 'C:\\',
dir: 'C:\\Users\\Decider\\Desktop\\the-complete-node\\ne-revision-1',
base: 'index.js',
ext: '.js',
name: 'index'
} */

Os module
const os = require('os') // npm i os
const totalMemory = os.totalmem()
const freeMemory = os.freemem()

console.log(totalMemory);
console.log(freeMemory);

Fs module
const fs = require("fs"); // npm i fs
/* const readDir = fs.readdirSync('./')
console.log(readDir); */

// “$” instead keep dirname (we should give directory)


fs.readdir("$", function (err, files) {
if (err) {
console.log(err);
} else {
console.log(files);
}
});
Event Emitter
- EventEmitter is one of the core classes in Node that allows us to raise (emit) and
handle events. Several built-in classes in Node derive from EventEmitter.

The emitter.on method will be called only if it was above the emitter.emit method.

// without arguments

const EventEmitter = require('events')


const emitter = new EventEmitter()

emitter.on('raisedEvent', ()=>{
console.log('an event happened');
} )

emitter.emit('raisedEvent')

// with arguments

emitter.on('raisedEvent', (arg)=>{
console.log('an event happened', arg);
} )

// passing args
emitter.emit('raisedEvent', {id: 11, url: 'https://'})

- To create a class with the ability to raise events, we should extend EventEmitter:
class Logger extends EventEmitter {
}
// logger.js

const EventEmitter = require("events");

class Logger extends EventEmitter {


log(message) {
console.log(message); // send an http request

this.emit("messageLogged", { id: 1, url: "http://" }); // raise an event


}
}

module.exports = Logger;
//app.js

const Logger = require('./logger');


const logger = new Logger()

logger.on("messageLogged", (arg) => {


console.log('Listener called', arg);
});

logger.log('message');
HTTP module
// ex 1
const http = require("http");
const server = http.createServer();

server.on("connection", (_) => {


console.log("New Connection...");
});

server.listen(3000);

// ex 2
const http = require("http");
const server = http.createServer((req, res) => {
if (req.url === "/") {
res.write("this is /");
res.end();
}

if (req.url === "/profile") {


res.write("this is /profile");
res.end();
}
});

server.on("connection", (_) => {


console.log("New Connection...");
});

server.listen(3000);
Node.js Web Server
Index.js
const http = require("http"); // npm i http
const fs = require("fs"); // npm i fs

const server = http.createServer((req, res) => {


if (req.url === "/") {
res.writeHead(200);
res.write("Hello Node - welcome to home page");
res.end();
}
if (req.url === "/login") {
res.writeHead(200);
res.write("Hello Node - welcome to login page");
res.end();
}
if (req.url === "/welcome") {
fs.readFile("index.html", (error, data) => {
if (error) {
res.writeHead(404);
res.write("Error: File Not Found");
} else {
res.writeHead(200, { "Content-Type": "text/html" });
res.write(data);
}
res.end();
});
}
});

const port = 3000;

server.listen(port, (error) => {


if (error) {
console.log("There was an error", error);
} else {
console.log(`Listening on port ${port} ....`);
}
});
NPM:
So, in this section, you learned that:

- Every Node application has a package.json file that includes metadata about the
application. This includes the name of the application, its version, dependencies,
etc.

- We use NPM to download and install 3rd-party packages from NPM registry:

- All the installed packages and their dependencies are stored under
node_modules folders. This folder should be excluded from the source control.

- Node packages follow semantic versioning: major.minor.patch


- Useful NPM commands are:
// Install a package
npm i <packageName>

// Install a specific version of a package


npm i <packageName>@<version>

// Install a package as a development dependency


npm i <packageName> —save-dev

// Uninstall a package
npm un <packageName>

// List installed packages


npm list —depth=0

// View outdated packages


npm outdated

// Update packages
npm update

- To install/uninstall packages globally, use -g flag.

Ex 1:
npm i -g npm@latest // to install npm globally in the system

npm init (or with by default values npm init --yes) – will create package.json file which
contains authors, dependencies, license,..
Ex 2:
// npm i underscore – to find all methods of this package go to underscore.js

var us = require('underscore')

// how require finds a module


// core module
// file or folder
// node_modules

const result = us.invoke([[11,9,8],[3,4,2]], 'sort');


console.log(result);

Ex 3:
// SemVer (semantic version)
Major.Minor.Patch
"mongoose": "^8.1.1", // 8.x
"underscore": "~1.13.6" // 1.13.x
"underscore": "1.13.6" // 1.13.6

Ex 4: viewing dependencies and versions


npm view mongoose dependencies
npm view mongoose versions

Ex 5: installing specific version of a package


npm i [email protected]

Ex 6: updating local packages


// updating local packages
npm outdated // shows all outdates packeges
npm update // will update the package but not updates the package.json
npm i -g npm-check-updates // installing ncu package
ncu -u // updates the package.json file with current version of package
npm i // then it will install the current version of all dependencies

Ex 7: installing packages in devDependencies, previous are application dependencies


npm i jshint --save-dev

Ex 8: uninstalling a package
npm un mongoose

Ex 9: working with global packages


npm i -g mongoose // installing package globally
npm -g outdated // gets globally outdated package
npm un -g mongoose // uninstalls a package globally

Ex 10: publishing a package


module.exports.add = function (a,b) { return a+b }

npm login
npm publish (// if error give it a unique name)

usage of published library:


npm i decidi-lib
var test = require('decidi-lib')
console.log(test.add(10,1));

Ex 11: updating published package


module.exports.add = function (a, b) {
return a + b;
};

module.exports.multiply = function (a, b) {


return a * b;
};

npm publish
then check in other files where previous version is used
npm outdated
npm update
ncu -u
var test = require('decidi-lib')
console.log(test.multiply(10,1));

You might also like