Node - Simple
Node - Simple
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.
- 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.
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");
setTimeout()
clearTimeout()
setInterval()
clearInterval()
- 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 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"
// app.js
- Node has a few built-in modules that enable us to work with the file system, path
objects, network, operating system, etc.
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); */
The emitter.on method will be called only if it was above the emitter.emit method.
// without arguments
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
module.exports = Logger;
//app.js
logger.log('message');
HTTP module
// ex 1
const http = require("http");
const server = http.createServer();
server.listen(3000);
// ex 2
const http = require("http");
const server = http.createServer((req, res) => {
if (req.url === "/") {
res.write("this is /");
res.end();
}
server.listen(3000);
Node.js Web Server
Index.js
const http = require("http"); // npm i http
const fs = require("fs"); // npm i fs
- 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.
// Uninstall a package
npm un <packageName>
// Update packages
npm update
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')
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 8: uninstalling a package
npm un mongoose
npm login
npm publish (// if error give it a unique name)
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));