Posts

Showing posts from 2022

Deploy NodeJS Project in Ubuntu Server

Image
Let's See The Standard Way To Deploy NodeJS  Project with Nginx  Firstly I assume you already connected to your Ubuntu server. Now first command which you need to run is ~ sudo apt-get update (This command will update all default packages of ubuntu server with latest versions) Now let's install Nginx server ~ sudo apt install nginx Now you have to install Node JS and NPM (Please read this article for it) Now you can check with ~ nginx -v ~ node -v ~ npm -v  NodeJS - Education Funda In each above commands version should be written if not it means it not installed properly in your server. now go to cd /var/www directory -> From here create directory sudo mkdir domain.xyz . -> cd domain.xyz . From here take clone from your GIT branch ( Reference Link ) Now go to ~ cd yourCloneDirectory . -> From this directory just run your project ~  node app.js/server.js (your root file of node js project) Now just call your IP or Domain in your browser your project should run now .

Git Clone From Specific Branch

Image
For clone code from specific branch we can use below command: GIT - Education Funda - git clone -b branchName cloneUrl  Lets see some of the top and most commonly asked interview question related to GIT . I hope this quick tip will be helpful for you. Happy Coding !!

Installing Node.js in Ubuntu Server PPA

Image
Installing Node.js in Ubuntu Server with Apt Using a NodeSource PPA Node JS Installation - Education Funda To install a different version of Node.js, you can use a PPA (personal package archive) maintained by NodeSource. These PPAs have more versions of Node.js available than the official Ubuntu repositories. Node.js v14, v16, and v18 are available as of the time of writing. First, we will install the PPA in order to get access to its packages. From your home directory, use curl to retrieve the installation script for your preferred version, making sure to replace 18.x with your preferred version string (if different). curl -sL https://deb.nodesource.com/setup_18.x -o nodesource_setup.sh --------------------- You can inspect the contents of the downloaded script with nano (or your preferred text editor): nano nodesource_setup.sh ---------------------------- Running third party shell scripts is not always considered a best practice, but in this case, NodeSource implements their own logi

Loading GIF Loader In Center of Webpage

Image
While page is loading sometimes it takes too much time for that time duration we can show GIF loader or any kind of loader to the users so users can know easily something is happens. Add Loader To Your Webpage   Such as your webpage html code is like below: <body>     <div class="content">         Long Content Here         <br/>         Click to view loading image.     </div>     <div id="divLoading" style="display:none">     </div> </body> We added one div here with the ID divLoading, you can take any ID selector as per your need. Now in webpage you need to add css code so that loader can be show in center of page at any screen size: <style type="text/css">      #divLoading.show      {          display : block;          position : fixed;          z-index: 100;          background-image : url('spinner.gif');          background-color:#666;          opacity : 0.4;          background-repeat

Node JS Convert 404 API Route to Proper Message

Image
We Generally Face A Problem of Bad Error Handling If Route Not Found in Node JS, Let's See How Can We Fix This Error Handling in Node JS Via adding below 4 lines code in our main node js file, we can manage it easily: //404 error handling app . use (( req , res ) => { const error = new Error ( "Not found." ) req . code = 1 req . statusCode = 404 ResponseMiddleware ( req , res , error . message ) }) That's it ! Happy Coding !

Manage Validations with Node Input Validator in Node JS

Image
Standard Way to Manage Validations in Node JS with Node Input Validator Package Node JS - Education Funda As per standard code in node js we should prefer manage validations in separate directory and files it means we can create separate directory such as validations and inside it we can create index.js file which is common file and manage separate validation for each module such as userValidatoin.js, postValidation.js etc. Something like this we can manage directory structure. Let's go deep into code now:- validations/index.js file: const validator = require ( "node-input-validator" ) const ResponseMiddleware = require ( "../middlewares/ResponseMiddleware" ) const fn = require ( '../helpers/functions' ) module . exports = { //common function to send validation response validate : ( v , res , next , req = null ) => { console . log ( "ValidatorsIndex => validate" ) if ( v . check (). then ( function ( ma

NodeJS Standard Way to Write Models with Sequelize

Image
As we all know in our node js project there is one main file which is generally index.js or app.js . so if we put all code related to models file load so that is not an standard way of coding so for solving this problem we can create model directory , inside this directory we can create one index.js file in which we load all the models then call in models/index.js file in our main file.  Node JS Here is our app.js file: "use strict" require ( 'dotenv' ). config (); //for calling process.env.VAR_NAME globally const server = require ( './config/server' ), express = require ( 'express' ), app = express (), port = server . port ; require ( './src/models' ); // all routing app . get ( '/' , ( req , res ) => { res . send ( server . appName ) }) app . use ( '/api' , require ( './src/routes/index' )); //listen server on mentioned port app . listen ( port , "0.0.0.0" , () => { console . log ( `

Authenticate Node JS Rest APIs With JWT

Image
Let's See How We Can Authenticate Node JS Rest APIs With JWT Package Firstly install the jwt package in your node js project via below command: $ npm install jsonwebtoken Create User Token For creating token we can manage it in middleware . Let's say create AuthMiddleware.js file: const jwt = require ( 'jsonwebtoken' ); const createUserToken = async ( id , email ) => { try { const token = jwt . sign ({ "user_id" : id , "email" : email }, process . env . JWT_TOKEN_KEY , { expiresIn : process . env . JWT_TOKEN_EXP //2h, 30d }) return token } catch ( err ){ return '' } } module . exports = { createUserToken } Now in controller we can call this function for create token. Let's say we have UserControoler.js file inside which we are creating user token: const AuthMiddleware = require ( '../middlewares/AuthMiddleware' ); const create = async ( req , res , ne

How To Check MongoDB ID Valid Or Not

Image
As you must aware about the object ID in mongo database or MongoDB is 24 characters long so for check is it valid id or not there is no direct validation method in validations package such as node-input-validator. MongoDB - Education Funda So for checking entered id is valid or not we can us below tech-tics: Approach 1 - Simple JS Validation var checkForHexRegExp = new RegExp("^[0-9a-fA-F]{24}$") checkForHexRegExp.test("i am a string") // false checkForHexRegExp.test("5e63c3a5e4232e4cd0074ac2") // true Approach 2 - With Mongo DB Method (Best Way) var ObjectID = require("mongodb").ObjectID ObjectID.isValid("i am a string") // false ObjectID.isValid("5e63c3a5e4232e4cd0274332") // true With Node Input Validator You Can Use Below Method: const id_exists = "required|string|minLength:24|maxLength:24|idExists"   const validator = require ( "node-input-validator" ) const mongoose = require ( 'mongoose

OG Tags For Social Media Sharing

Image
Share On Social Media OG Tags For Proper Title, Description and Image Social Sharing Step 1: Title Maximum of 65 characters <title>your keyword rich title of the website and/or webpage</title> Step 2: Description Maximum of 155 characters <meta name="description" content="description of your website/webpage, make sure you use keywords!"> Step 3: og:title Maximum 35 characters <meta property="og:title" content="short title of your website/webpage" /> Step 4: og:url Full link to your webpage address <meta property="og:url" content="https://www.example.com/webpage/" /> Step 5: og:description Maximum 65 characters <meta property="og:description" content="description of your website/webpage"> Step 6: og:image Image(JPG or PNG) of size less than 300KB and minimum dimension of 300 x 200 pixel is advised <meta property="og:image" content="//cdn.example.com/uplo

Check Image URL Exists Or Not WIth PHP

Image
How To Image Or Any File Exists Or Not With PHP Language For checking the URL is exists or not we can use curl request in PHP and we can use same approach in other programming languages also such as JavaScript. So for PHP URL check code is below: function is_url_exist($url){     $ch = curl_init($url);         curl_setopt($ch, CURLOPT_NOBODY, true);     curl_exec($ch);     $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);     $status = ($code == 200) ? true : false; // single liner if else     curl_close($ch);     return $status; } Thanks for reading this blog, I hope it will be helpful for you and please share your feedback in comments section.

Get YouTube Video Thumbnail And Use It With Your Code

Image
Download Any YouTube Video Thumbnail YouTube stores many different types of thumbnails on its server for different devices. You can access it by using the video id which every YouTube video has. You can display the images on your website using a variable $link which holds the id of the video and substituting it in the place for video_ID in the link. Download-Any-Youtube-Video-Thumbnail   Low quality thumbnail: https://img.youtube.com/vi/<YouTube_Video_ID_HERE>/sddefault.jpg Medium quality thumbnail: https://img.youtube.com/vi/<YouTube_Video_ID_HERE>/mqdefault.jpg High quality thumbnail: https://img.youtube.com/vi/<YouTube_Video_ID_HERE>/hqdefault.jpg Maximum quality thumbnail: https://img.youtube.com/vi/<YouTube_Video_ID_HERE>/mqdefault.jpg Such as in this blog we will get thumbnail of this YouTube video: Example: If you want to access the thumbnail of this above video: So the Video ID for this video is: aCB2WRqxxvo So, this is how video thumbnail link looks l

How To Save CK Editor Data Into Database

Image
The "CK Editor" is an HTML editor in which for saving the data into db we can use below function before saving it into DB in PHP language.   function dataready($data) {           $data = trim($data);           $data = stripslashes($data);           $data = htmlspecialchars($data);           return $data; } Before saving data we can call this function now: dataready($_POST['input_name']);  For for showing data into view pages we can use: html_entity_decode($var_article_text); Thanks for reading this blog I hope it will helpful for you.