Skip to content

Instantly share code, notes, and snippets.

@ishanajmeri
Created June 3, 2020 13:39
Show Gist options
  • Save ishanajmeri/a7524711f8afe69efd22f54eefd46b6c to your computer and use it in GitHub Desktop.
Save ishanajmeri/a7524711f8afe69efd22f54eefd46b6c to your computer and use it in GitHub Desktop.

?

  • Node.js is an open-source and cross-platform runtime environment that executes JavaScript code outside of a browser.Which is used of buliding backand services called as Apllication Programming Interface.
  • use for prototyping and agile development.
    • prototype id an object that is associated with every functions and objects by default in JavaScript(similar to the constructor)
  • Node is a runtime environment for executing JS code.

The module wraper

  • Every file in a Node application is a module.Node automatically warps the code in each file with an IIFE(Immediately-invoked Function Expression) to create scope.So,variable and fuctions defined in one file are only scoped to that file and not visible to other files unless explicitly exported.
(function (exports, require, module, __filename, __dirname) {
  //Module code actually lives in here
});

reqire(id)

  • Used to import modules, JSON and localfiles.
const moduleFromOtherFile = require('./path');
const jsonData = require('./path/filename.json');
const moduleFromNode_modules(default) = require('./name');

path module

  • path.parse(path) method returns an object whose properties represent significant elements of the path.

Eventemitter

  • All objects that emit events are instances of the EventEmitter class.
  • The eventEmitter.on() method is used to register listners, while the eventEmitter.emit() method is used to trigger the event.
  • To create a class with the ability to raise events, we should extend EventEmitter :
class Logger extends EventEmitter {}

http

  • use of http.createServer()
  • The JSON.stringify is an inbuilt function in JSON which allows us to take a JavaScript object or array and create a JSON string out of it.
JSON.stringify(value, replacer, space);

REST

  • REST stands for REpresentational State Transfer. It is a software architectural style that defines a set of contraints to be used for creating Web services.
  • It is used to access and manipulate data using several stateless operation. These operations are integral to the HTTP protocol and represent an essential CRUD functionality (Create, Read,Update,Delete).
  • The HTTP operation available are:
    1. POST(create a resource or generally provide data)
    2. GET(retrieve an index of resources or an individul resource)
    3. PUT(create or replace a resource)
    4. PATCH(update/modify )
    5. DELETE(remove a resource)

Express

  • Express is a minimal and flexible Node.js web application framework that provides a robust set of features to develop web and mobile applications.
Middleware
  • Middleware is a subset of chained Express js routing layer before the user-defined handler is invoked.

  • Middleware funciton are functions that have access to the request object(req), the reponse object (res), and the next middleware function in application's request-response cycle.

function log(req, res, next) {
  console.log('Logging..');
  next();
}
  • We can detect the enviroment in which our node application is running (development(default),production ) using process.env.NODE_ENV and app.get('env').
Helmet
  • Helmet is a type of middleware for Express based applications that automatically sets HTTP headers to prevent sensitive information from unintentionally being passed between the server and client.
Morgan
  • Morgan is a HTTP request logger middleware for Nodejs. It simplifies the process of logging requests to your application.
app.use(morgan('tiny'));

nodemon

  • It is a tool that helps develop node.js based application by automatically restarting the node application when file changesin the directory are detected.
npm install -g nodemon
  • To run command in terminal
nodemon [your node app]

Node-config

  • It allows us to define a set of default parameters and extend them for different deployment environments(development, production).
  • config.get() will throw an exception for undefined keys to help catch typos and missing values.

debug

  • We can use the debug package to add debugging information to an appliction.
const debug = require('debug')('app:startup');
// use
console.log('imformation');
debug('imformation');
  • need to set environment variable DEBUG in terminal so that you can see only that app name debug in terminal:
export DEBUG=app:startup

Template Engine

  • Template engine helps to create an HTML template with minimal code. It can inject data into HTML template at the client side and produce the final HTML.
  • At run time, template engines replace variables in our file with actual values, and then send the resulting HTML string to the client. Template engines :
    1. pug
    2. mustache
    3. ejs
  • Set up view engine(pug):
app.set('view engine', 'pug');

database integration

  • Database integration is the process used to aggregate information from multiple sources-like social media,sensor data from IoT and more.

Asnchronous JavaScript

  • There are 3 patterns to deal with asnchronous code:

    1. callbacks
    • A callback is nothing more than a function passed as a parameter to another function.
    • Callback hell : All code after an asynchronous operation is nested inside a function.More operation, much less readable code.
    doThing('value', (err, result) => {
      if (err) {
        // handle error here
        console.error(err);
      } else {
        // handle success here
        console.log(result);
      }
    });
    1. promises
    • Promise is a object that holds the eventual result of an asynchronous operaton
    const promise = new Promise((resolve, reject) => {
      // function
    });
    • Arguments resolve and reject are callbacks provided by JavaScript itself.
    • resolve(value) - if the job finished successfully,with result value.
    • reject(errror) - if an error occurred, error is the error object.
    • consumers:then,catch,finally
    1. async/await
    • A function that returns an AsyncFunction object.
    const value = await promise;
    • The keyword await makes JavaScript wait until that promise setteles and returns its result.
      async function(){
        //handle function
      }
    • The word async before a function means one simple thing: a function always returns a promise. We have to decorate function with async for the promise.

Mongodb

  • MongoDB is an open-source document database and leading NoSQL database.
start
    1. In terminal mongod.
    2. In vscode terminal nodemon filename.
create
mongoose
  .connect('mongodb://localhost/servername')
  .then(() => console.log('connnected'))
  .catch(() => console.log('connection failed'));
schema
const courseSchema = new mongoose.Schema({
  name: String,
  //data entries like states in react
});

const Course = mongoose.model('Course', courseSchema);

async function createCourse() {
  const course = new Course({
    name: 'name',
    //data fill
  });
  const result = await course.save();
}

creactCourse(); //sending to mongodb
querying documents
// eq(equal)
// ne(not equal)
// gt(greater than)
// gte(greater than or equal to)
// lt(less than)
// lte(less than or equal to)
// in
// ein(not in)
async function getCourses() {
  const courses = await Course.find({ price: { $gte: 10 } }) //give me course which price is greater than 10
    .or([{ author: 'this' }, { something: 'that' }]) // give me author of this OR something of that.
    .limit()
    .sort()
    .select()
    .count(); // number of total courses
}
getCourses(); //function call
updating documents
async function updateCourse(id) {
  const course = await Course.findById(id);
  if (!course) return;
  course.set({
    property: change_value,
  });
  const result = await course.save();
}

updateCourse(id);
validation
const courseSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
    minlength: Number,
    maxlength: Number,
    match: Regux,
  },
  category: {
    enum: ['name1', 'name2', 'name3'], //only valid for this array names
  },
  tags: {
    type: Array,
    validate: {
      validator: function (v) {
        return v && v.length > 0;
      },
      message: String,
    },
  },
  isPublished: Boolean,
  price: {
    type: Number,
    required: function () {
      return this.isPublished; //required validation is depand on the value of isPublished
    },
  },
});

Authentication & Authorization

  • Authentication is the process of verifying the identity of a person.
  • Authorization is the process of giving someone permission to do something.

lodash

  • pick
_.pick(object, [paths]);

var object = { a: 1, b: '2', c: 3 };
_.pick(object, ['a', 'c']);
// => {'a' : 1, 'c' : 3}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment