Node Js - Javascript

Basic


  • Theory
    • Node JS REPL
      • Read-Eval-Print-Loop is an interactive shell that processes Node.js expressions
    • npm
      • Node Package Manager helps to manage package inside Node.js
  • Password
    • Hash Table => One way function from Password to Hash
    • Rainbow Table => Collection of common Password and its Hash
    • Salt => Added in the user password to make it less common to decode, Stored in Database
    • Pepper => Added along with Salt but not stored in DB
    • When User Login, We give a Token to that User using JSON Web Token or Session Token
  • CommonJS Module
        // Import a custom File module
        const variable = require("filePath");
        // Import a Built-in Module
        const variable = require("fileName");
    
        // Export the Function
        module.exports = functionName;
        // Export multiple things as a object
        module.exports = {functionName1, functionName2};
        // Export a key-value pair by module.exports object
        module.exports.key = value;
        // File automatically gets wrapped by this function when exported
        function(exports, require, module, __filename, __dirname) {
            // Statements
        }
    
  • ECMA Script Module/ES6 Module
        // ES6 syntax will be used if file extension is .mjs
        export function functionName1() {
            // Statements
        }
        // Add "type": "module" in package.json before use
        import {functionName1} from "filePath" ;
        // Import functionName2, functionName3 by their name as they are not exported by default
        import {functionName2, functionName3} from "filePath";
    
        // Export a Function by default
        const functionName1 = () => {
            // Statements
        }
        // Export this functionName1 by default from file1
        export default functionName1;
        // Import functionName1
        import functionName1 from "filePath";
    
        // Import functionName2 as variable
        import {functionName2 as variable} from "filePath";
        // All function will get Imported as variable
        import * as variable from "filePath";
        // Can access function like this
        variable.functionName
    

Built-in Modules


FS

  • const fs = require('fs')
  • fs.readFile('file.txt', 'utf-8', (err, data) => {statement}) => Reads the entire contents of a file
  • var = fs.readFileSync('file.txt', "utf-8") => Reads the entire contents of a file and Returns a Buffer in Synchronous
  • var.replace("value1", "value2") => Replace value1 from var to value2
  • fs.writeFile('file.txt', "data", () => {statement}) => Write in a file, Create a file if needed, Data can be a String or Buffer
  • fs.writeFileSync("file.txt", data) => Write in a file, Create a file if needed, in Synchronous

HTTP

  • const http = require('http')
  • const port = process.env.PORT || 3000 => Port that the process is getting or Run or port 3000
  • Create Server
        const server  = http.createServer((req,res) => {
            url = req.url // Access the URL
            res.statusCode = 200 // Response code for URL request
            res.setHeader("content-type", "file-type") // Type of content sent by server
            res.writeHead(responseCode, {"content-type": "file-type"}) // Combination of status code and set header
            res.end(var) // Serve your content
        })
    
  • Listen to the url requests made
        server.listen(port, hostname, () => {
            console.log()
        })
    

OS

  • const os = require('os')
  • os.freemem() => Returns the amount of free system memory in bytes as an integer
  • os.homedir() => Returns the string path of the current user's home directory
  • os.platform() => Returns a string identifying the operating system platform
  • os.release() => Returns the operating system as a string
  • os.type() => Returns the operating system name as returned by uname(3)
  • os.version() => Returns a string identifying the kernel version
  • os.hostname() => Returns the host name of the operating system as a string

Path

  • const path = require("path")
  • path.basename(path) => Returns the last portion of a path
  • path.dirname(path) => Returns the directory name of a path
  • path.join("paths") => Returns string with the complete normalized path containing all the segments
  • path.join(__dirname, "..") => Getting the directory path one folder above, __dirname gives file path
  • path.extname(path) => Returns the extension of the path

URL

  • const url = require("url")
  • const myURL = new URL('https://example.org:8000') => Out put will be https://example.org:8000/a/b/c?d=e#fgh
  • myURL.pathname = '/a/b/c' => Add a Path name
  • myURL.search = '?d=e' => Add get parameter
  • myURL.hash = '#fgh' => Add hash, Used when navigating in a particular section of a page
  • console.log(myURL) => Prints complete URL object
  • console.log(myURL.href) => Prints href from URL object

Events

  • const var = require("events")
  • class myEvent extends var {} => Creating a custom event class
  • myEvent.on("eventName", () => {statement;}) => Creating a function for our custom event
  • myEvent.emit("eventName") => Firing the custom event

External Modules


Express

  • const express = require("express")
  • const app = express() => Object corresponding to HTTP
  • const port = value
  • Serve a file at a particular URL
        app.get("URL", (req, res) => {
            res.send("value") // Display a value
            res.status(n) // Set a status code
            res.sendFile("folderName") // Send a file from the directory path
            res.sendFile(path.join(__dirname, "filePath")) // Send a HTML file
            res.json({ "key": value }) // Send a JSON
        })
    
  • app.get('/URL/:var', (req, res) => {}) => Send a parameter with URL
  • In app.use Folder
        const router = express.Router();
        router.post("URL", (req, res) => {
            const var = var1(req.body) // var1 is a schema
            var.save(); // Saving in the Mongo Compass connected
            statement;
        });
        module.exports = router;
    
  • Listen the Req
        app.listen(port, () => {
            console.log(`App listening at http://localhost:${port}`);
        });
    
  • app.use(path, callback) => Used to mount the specified middleware function at path which is being specified
  • app.use("URL", express.static("folderName")) => Serve static file
  • app.use("URL", require("folderName")) => Serve this folder at given URL, To better organize the folder structure
  • app.use(express.urlencoded()) => Used to get encoded data when form is submitted
  • Custom middleware function
        const var = (req, res, next) => {
            statement;
            next(); // Pass control to the next middleware function
        }
        app.use(var) // Call the function
    
  • POST Request
        app.post("URL", (req, res) => {
            req.body.var // Access encoded data from form
        })
    
  • res.status(n).send("") => Send status code with res.send
  • req.params.var => Access the req URL variable that is passed as parameter

Mongoose

  • const mongoose = require("mongoose") => Import mongoose
  • const mongoURI = "string" => String received for Mongo Compass to connect to Database
  • Connect to Database
        const connectToMongo = () => {
            mongoose.connect(mongoURI, () => {
            console.log(""Connected to Mongo Successfully"");
            });
        };
        module.exports = connectToMongo;
    
  • const { Schema } = mongoose;
  • Create a Schema
        const UserSchema = new Schema({
            email: { // Name
            type: String, // Data Type
            required: true, // Require to Fill
            unique: true, // Unique
            default: value, // Default Value
            }});
        module.exports = mongoose.model("user", UserSchema);
    
  • mongoose.model("modelName", var) => Make a Model from Schema, First parameter is Model name and 2nd is Schema
  • mongoose.connection.once("open", function() {statement})
  • var = new mongoose.schema({ key: value })
  • var.methods.speak = function() {statement})
  • var.save(function (err, var) {statement})

View Engines


PUG

  • const app = express()
  • app.set("view engine", "pug") => Set the template engine
  • app.set("views", path.join(__dirname, "views"))
  • res.render("fileName", var) => Like .sendFile but used to serve template
  • req.body => Access values submitted by form using name attribute

Express Handlebars

  • `var exphbs = require("express-handlebars") => In app.js file
  • const app = express()
  • app.engine("handlebars", exphbs())
  • app.set("view engine", "handlebars") => Set the templete engine
  • views > layouts > main.handlebars is used for basic template
      app.get("URL", (req, res) => {
        res.render("home") // To serve home.handlebars file inside views folder
      })
    
  • res.render("fileName", {var: value}) => Send variable
  • PUG

Packages


  • nvm install vN.N.N => Install a particular node version
  • nvm use vN.N.N => Use a particular node version
  • Nodemon
    • npm i -g nodemon
    • nodemon index.js
Share: