Skip to main content

Posts

Showing posts from June, 2019

Machine Learning in Frontend Development

What is Machine Learning by Examples? Making computers able to identify cats or dogs or anything in an image. Making computers able to predict the future. Some of Algorithms that makes it possible Naive Bayes K-Nearest Neighbour (KNN) Linear Regression Convolutional Neural Networks (CNN) LSTM - Long Short Term Memory Types of Algorithms Supervised Learning Unsupervised Learning Reinforcement Learning What is Supervised Learning? Create predictive models based on a set of features and labels. Example, predicting price of a house based on other houses sold in the area. Features are characteristics of the entries in the dataset. Label would be the prices of the houses. Another example is customer clustering in a supermarket based on buying habits, time of buying, frequency, etc. Another example is sign language to text or speech conversion. One of the ways to use supervised learning in frontend development is setting alt text of images, adding tags to content, e...

Using Mongoose search a MongoDB Database Collection for a document with matching element in an array

Using Mongoose search a MongoDB Database Collection for a document with matching element in an array Schema const mongoose = require ( 'mongoose' ); const Schema = mongoose . Schema ; const personSchema = new Schema ({ name : String , favouriteFoods : [ String ] }); module . exports = mongoose . model ( 'Person' , personSchema ); Problem Find a person who has 'Sushi' in its array of favoriteFoods. Solution Person . find ({ favouriteFoods : "sushi" }) . then ( person => console . log ( person )) . catch ( err => console . error ( err )); That's it folks. Ask questions in the comments.

Validating Query Parameters Using Express Validator

Here is how to validate query parameters using express validator. To check for variables in query params, i.e., req.query, use  query([fields, message]) . Same as  check([fields, message]) , but only checking  req.query . Example: Installing express-validator npm install -- save express - validator Importing query const { query } = require ( 'express-validator/check' ); Using query router . post ( '/add-product' , isAuth , [ query ( 'title' ) . isString (). withMessage ( 'Only letters and digits allowed in title.' ) . trim () . isLength ({ min : 3 }). withMessage ( 'Title too short. Enter a longer title!' ), query ( 'price' , 'Enter a valid price.' ) . isFloat (), query ( 'description' ) ...

Allow File Input To Accept Only Image Or Only Doc And Pdf File

Allow file input to accept only image or only doc and pdf file For Image upload < input type = "file" accept = "image/x-png,image/jpg,image/jpeg" > For Image with Gifs < input type = "file" accept = "image/x-png,image/jpg,image/jpeg,image/gif" > For doc, docx and pdf files < input type = "file" accept = "application/pdf, application/msword, application/vnd.openxmlformats-officedocument.wordprocessingml.document" > For Presentation Upload < input type = "file" accept = "application/pdf,application/vnd.ms-powerpoint,application/vnd.openxmlformats-officedocument.presentationml.slideshow,application/vnd.openxmlformats-officedocument.presentationml.presentation" /> For Excel file upload < input type = "file" accept = "application/vnd.ms-excel" > That's it folks. Let me know in the comments if you need more with respect to ...

Logging for Express - Logging Requests through Morgan Middleware

Logging requests for your Express App can be accomplished using Morgan. It is a simple to use package. HOW TO INSTALL? Install Morgan using Node Package Manager (NPM) npm install --save morgan HOW TO INCLUDE? Include Morgan middleware in your application in the following way in the main app.js/server.js const morgan = require('morgan'); HOW TO USE? Finally use it as a middleware after creating express instance. app.use(morgan('combined')); On running your application, you will see logs being printed on server side console. One of the example of logs is as follows: ::1 - - [28/Jun/2019:06:07:27 +0000] "GET / HTTP/1.1" 304 - "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36" SAVE LOGS TO FILE Import fs module into your express app const fs = require ( 'fs' ); Set a constant that will write incoming logs into a file named access.log ...

Compression for Express - Compress program files

Compression for Express is commonly used to compress the size of your code files in Express apps. It is a middleware. It does not compress other files such as images. Generally compression is also provided by your server provider. But in case they do not, this is a easy and sure way to send compressed program files to the client, making your website run faster. HOW TO INSTALL? Install Compression using Node Package Manager (NPM) npm install --save compression HOW TO INCLUDE? Include Compression in your application in the following way in the main app.js/server.js const compression = require('compression'); HOW TO USE? Finally use it as a middleware after creating express instance. app.use(compression()); That's it folks, you are set!

Helmet for Express - Setting up Security for Your Web Application

Helmet for Express is commonly used for setting up Security for Your Web Application. It is group of middleware for security. HOW TO INSTALL? Install Helmet and Express using Node Package Manager (NPM) npm install --save express npm install --save helmet HOW TO INCLUDE? Include Helmet and Express in your application in the following way in the main app.js/server.js const express = require('express'); const helmet = require('helmet'); HOW TO USE? Finally use it as a middleware right after creating express instance. const app = express(); app.use(helmet()); That's it folks, you are set!

Web Scraping REST API with Node, Express and Puppeteer

Web Scraping REST API with Node, Express and Puppeteer Step 1. Create a Node project Create a folder. Open the folder using a terminal. Type:  npm init  and press enter Answer or leave unanswered the questions asked by the program. Your Node Project is ready. Step 2. Install Puppeteer and Express  Run npm install --save express in the terminal. Run  npm install --save puppeteer  in the terminal. This installs puppeteer as well as an instance of browser. Step 3. Create Web Scraping Program Create a file named app.js Add the following lines to app.js const express = require ( 'express' ) const scraper = require ( './utils/scraper' ) const app = express (); app . get ( '/reviews' , ( req , res ) => { scraper . extractReviews ( req . query . url ) . then ( data => { res . status ( 200 ). json ({ message: "success" , data: data }) }). catch ( err => res . status ( 500 ). json ({ me...

Taking Website Screenshot with Node and Puppeteer

Taking Website Screenshot with Node and Puppeteer Step 1. Create a Node project Create a folder. Open the folder using a terminal. Type: npm init and press enter Answer or leave unanswered the questions asked by the program. Your Node Project is ready. Step 2. Install Puppeteer Run npm install --save puppeteer in the terminal. This installs puppeteer as well as an instance of browser. Step 3. Create Program Create a file named app.js Add the following lines to app.js const puppeteer = require ( 'puppeteer' ); ( async () => { const browser = await puppeteer . launch (); const page = await browser . newPage (); await page . goto ( 'https://www.google.com/' ); await page . screenshot ({ path: 'example.png' }); await browser . close (); })(); Run node app.js in terminal Tadaaaaa! Check the folder for a new image names example.png

Using Multer Upload Files From Two Fields of Separate Forms on Different Pages

Using Multer Upload Files From Two Fields of Separate Forms on Different Pages In this example I have two fields - resume and image. Resume in one form and Image in other. Both are on separate pages. First import dependencies const path = require ( 'path' ); // for getting file extension const multer = require ( 'multer' ); // for uploading files const uuidv4 = require ( 'uuidv4' ); // for naming files with random characters Define fileStorage and fileFilter const fileStorage = multer . diskStorage ({ destination : ( req , file , cb ) => { // setting destination of where the file to be stored if ( file . fieldname === "resume" ) { // if uploading resume cb ( null , 'resumes' ); } else { // else uploading image cb ( null , 'images' ); } }, filename : ( req , file , cb ) => { // naming file cb ( null , file . fieldname + "-" + uuid...

Cannot read property 'isLoggedIn' of undefined

If you are getting an error as follows: Cannot read property 'isLoggedIn' of undefined And you are using multer in the following fashion: const fileStorage = multer . diskStorage ({ destination : ( req , file , cb ) => { cb ( null , 'images' ); }, filename : ( req , file , cb ) => { cb ( null , new Date (). toISOString () + '-' + file . originalname ); } }); Then you must first understand what is the cause of the problem. new Date (). toISOString () is the cause of the problem. Solution: Either use  new Date().getMilliseconds().toString() Or use uuid for naming the stored file. UUIDV4 Get Started Installation $ npm install uuidv4 Quick start First you need to integrate uuidv4 into your project by using the  require  function: const   uuid   =   require ( ' uuidv4 ' ) ; Then you can create UUIDs. To do so simply call the  uuid  function: console . lo...