Remove array element inside for loop – Javascript

In this article, you will learn, how to remove an array element in a for loop using Javascript. We will be looping in reverse.

Video tutorial:

You can use the following code:

// sample array
const categories = [
  {
    category: "Laptop",
    products: ["Macbook pro", "Acer aspire 5", "Dell XPS", "Lenovo Ideapad"]
  },
  
  {
    category: "Mobile",
    products: ["Samsung Galaxy S23", "Apple iPhone 15"]
  }
]

// looping through all array elements in reverse
for (let a = categories.length - 1; a >= 0; a--) {
  // condition criteria
  if (categories[a].products.length > 3) {
    // remove array element
    categories.splice(a, 1)
  }
}

This will delete all categories having more than 3 products.

MongoDB GridFS

In this tutorial, you will learn, how you can upload, retrieve, and delete files using MongoDB GridFS.

Video tutorial:

Upload the file to MongoDB GridFS

First, in your Node JS file, you need to create an instance of your GridFS bucket. You can create as many buckets as you want.

// include MongoDB
const mongodb = require("mongodb")

// get MongoDB client
const mongoClient = mongogb.MongoClient

// connect with MongoDB server
const client = await mongoClient.connect("mongodb://localhost:27017")

const db = client.db("mongodb_gridfs")

// create GridFS bucket instance
const bucket = new mongodb.GridFSBucket(db)
  1. First, it includes the MongoDB module.
  2. Then it gets a Mongo client object that helps in connecting with the database.
  3. Then we connect to the server.
  4. After that, we set the database.
  5. And finally, we are creating an instance of a bucket.

You can also give your bucket a name to identify.

// create GridFS bucket instance named "myBucketName"
const bucket = new mongodb.GridFSBucket(db, {
  bucketName: "myBucketName"
})

Following POST route will save the file.

// npm install fs
const fs = require("fs")

// npm install ejs
app.set("view engine", "ejs")

// npm install express-formidable
const expressFormidable = require("express-formidable")
app.use(expressFormidable())

app.post("/upload", function (request, result) {
  // get input name="file" from client side
  const file = request.files.file
  
  // set file path in MongoDB GriDFS
  // this will be saved as "filename" in "fs.files" collection
  const filePath = (new Date().getTime()) + "-" + file.name
  
  // read user uploaded file stream
  fs.createReadStream(file.path)
  
    // add GridFS bucket stream to the pipe
    // it will keep reading and saving file
    .pipe(
      bucket.openUploadStream(filePath, {
        // maximum size for each chunk (in bytes)
        chunkSizeBytes: 1048576, // 1048576 = 1 MB
        // metadata of the file
        metadata: {
          name: file.name, // file name
          size: file.size, // file size (in bytes)
          type: file.type // type of file
        }
      })
    )
    // this callback will be called when the file is done saving
    .on("finish", function () {
      result.send("File saved.")
    })
})

Now if you check in your “mongodb_gridfs” database, you will see 2 new collections.

  1. fs.files
    • This will save all uploaded files.
  2. fs.chunks
    • This will save all chunks of each file with that file ID.

Fetch all files from MongoDB GridFS

The following GET route will fetch all files uploaded to MongoDB GridFS.

app.get("/", async function (request, result) {
  const files = await bucket.find({
    // filename: "name of file" // 
  })
    .sort({
      uploadDate: -1
    })
    .toArray()
  result.render("index", {
    files: files
  })
})

Now you need to create a folder named “views” and inside that folder create a file named “index.ejs”.

Then you can loop through all files and display them in the image tag.

<% if (files) { %>
  <% files.forEach(function (file) { %>
    <p><%= file.filename %></p>
    <img src="image/<%= file.filename %>" style="width: 200px;" />
  <% }) %>
<% } %>

Right now, you will see a broken image. Now we need to create an API that will return the image as a response.

Return image as API response

app.get("/image/:filename", async function (request, result) {
  // get file name from URL
  const filename = request.params.filename
  
  // get file from GridFS bucket
  const files = await bucket.find({
    filename: filename
  })
  .toArray()
  
  // return error if file not found
  if (!files || files.length == 0) {
    return result.status(404).json({
      error: "File does not exists."
    })
  }
  
  // it will fetch the file from bucket and add it to pipe
  // result response is added in the pipe so it will keep
  // returning data to the client
  bucket.openDownloadStreamByName(filename)
    .pipe(result)
})

Now you will be able to view the image.

Delete file from MongoDB GridFS

First, you need to create a button after each file.

<% if (files) { %>
  <% files.forEach(function (file) { %>
    <p><%= file.filename %></p>
    <img src="image/<%= file.filename %>" style="width: 200px;" />
    
    <form action="/files/del" method="POST">
      <input type="hidden" name="_id" value="<%= file._id %>" />
      <button type="submit" class="btn btn-danger">Delete</button>
    </form>
  <% }) %>
<% } %>

Then you need to create an API in your Node JS file.

// 
const ObjectId = mongodb.ObjectId

app.post("/files/del", async function (request, result) {
  // get ID from data
  const _id = request.fields._id
  
  // delete file from bucket
  await bucket.delete(ObjectId(_id))
  
  // return response
  result.send("File has been deleted.")
})

This will delete the file and all its chunks from the database. So that’s all for now if you face any problem in following this, kindly do let me know.

You can learn more about the grid file system from Mongo DB’s official website.

Manage website using Git – Shared, VPS, Dedicated

In this article, you will learn how you can manage your website, hosted on Shared, VPS, or dedicated server, using Git version control.

Video tutorial:

This tutorial works for all Shared, VPS, and dedicated hosting servers.

I have created a simple “Hello world” PHP file.

<?php

echo "Hello world";

I have created a sub-domain and Git repo on my shared hosting. You can check it from the video above.

Once a Git repo is created, it will give you an SSH path. I am going to open CMD in my folder and initialize Git in it.

cd "my-project-folder"
git init
git remote add origin ssh://adnantech@adnan-tech.com/home2/adnantech/git.adnan-tech.com
git status
git add .
git commit -m "Initial commit."
git push origin master

It will ask for your username and password. You can enter the credentials you use to log in to your hosting server.

If you receive the following error:

fatal: bad config value for ‘receive.denycurrentbranch’ in config

You can fix it by first accessing SSH from your terminal: (make sure to replace it with your username and IP address)

ssh -p 2222 adnantech@162.241.216.155

It will again ask for your password. Once the password is entered, you will be entered into the SSH terminal.

Once inside the SSH terminal, enter the following command:

which git-receive-pack

It will return the path of your Git receive pack. Copy it. Then push the code using the following command:

git push origin master -u --exec=your_git_receive_pack

Replace “your_git_receive_pack” with your Git receive-pack returned from the previous command.

I am going to make some changes in my code.

<?php

echo "Hello world of programming...";

Then I am going to push again.

git add -A
git commit -m "Changes made."
git push origin master -u --exec=your_git_receive_pack

You will now see updated code pushed to your website.

So that’s it. That’s how you can manage your shared, VPS, or dedicated server’s website code using Git.

You can watch the video if you are having problems following the article.

If you still face any issues with this, you can let me know.

More: Learn how to deploy Node JS app on VPS or dedicated hosting.

API to return image in Node JS

In this article, we will show you, how you can return an image from the response of an API in Node JS.

Video tutorial:

First, I will create an image tag and set the “src” attribute as the path of the API. I also send “adnan” as an argument so the server will know which image to fetch.

<img src="/showImage/adnan" />

Then I am going to create a GET API in Node JS.

const fs = require("fs")

app.get("/showImage/:name", async function (request, result) {
  const name = request.params.name
  const image = await db.collection("images")
    .findOne({
      name: name
    })
  if (image == null) {
    let defaultImage = await fs.readFileSync("public/default.jpg")
    defaultImage = Buffer.from(defaultImage, "base64")
    
    result.writeHead(200, {
      "Content-Type": "image/jpg",
      "Content-Length": defaultImage.length
    })
    result.end(defaultImage)
    return
  }
  
  const imageContent = await fs.readFileSync(image.path)
  
  result.writeHead(200, {
    "Content-Type": "image/jpg",
    "Content-Length": imageContent.length
  })
  result.end(imageContent)
  return
})

If you run the code now, you will be able to see the image.

Job Portal website in PHP and MySQL – MVC

A Job Portal website is created in PHP and MySQL using MVC architecture. MVC stands for Model-View-Controller and this architectural design is used by many websites for scalability.

Live Demo

  • ✅ Easy setup.
  • ✅ Compatible with almost every shared/dedicated/VPS hosting.
  • ✅ Free support.

New features:

  • ✅ Optimized sending bulk emails.

Files included:

  • .php
  • .css
  • .js

Tech stack:

  1. PHP +7.0
  2. MySQL +5.0
  3. Bootstrap 4
  4. Vue JS 3

Recruiter can post a job

Post job

Recruiter posted jobs

Recruiter uploaded jobs

Change status of applicant

Application status change

Edit/delete job

A recruiter can edit or delete any of his posted jobs at any time. This helps if the recruiter needs to change the requirements for a job or delete if the vacancy is already been filled.

Jobs Listing

Users will get a listing of all the jobs posted by recruiters.

Job listing

Job Detail

They can view the job details by clicking the job title.

Job detail

Filter Jobs

On the jobs listing page, users can filter jobs by the type of job they want, like developer, designer, etc. By the location to see if the job is in their city or if they can relocate to that city. Or by the nature of the job i.e. is the job part-time, full-time, or remote. Users can also search the jobs in their salary range. This way they can find jobs that pay them according to their needs.

Real-time updates on new jobs

Users will get real-time updates whenever a new job is posted by the recruiter. They do not have to refresh the page to check if there is any new job. To develop this feature, I have used sockets. You need to install Node JS in your system or server to make this feature work. Even if you do not have Node JS installed, all other features will work except for real-time job updates.

Email notifications of new jobs

Users can turn on notifications from recruiters. Whenever that recruiter posts a new job, all the users who have turned on their notifications will receive an email.

Admin can see all the stats

The admin of the website can see the total number of users registered. The total number of jobs that have been posted by recruiters. And the total number of applications that have been submitted for those jobs. The admin can see all this information on his dashboard.

Manage users

Admin will have the option to add new users to the website. While adding, he/she can select if the user be an applicant or a recruiter. Admin can also manage existing users. Admin can edit the user and can also delete the user if required. Admin can change the password of the user as well. This is helpful if the user is finding it difficult to receive the password reset email. Or if you want to prevent the user from logging in.

Deployment

This Job Portal website can be deployed on any server that supports PHP and MySQL.

Convert UTC to local timezone – Node JS

In this tutorial, we will teach you, how you can convert UTC time to your local timezone in Node JS.

Following code will first get the current datetime in UTC, then convert it to user local timezone.

Note: You do not need to provide the timeZone from client side. Node JS will automatically detect the timeZone from incoming request and convert it accordingly.

let date = new Date()

date = new Date(date + " UTC")
date = date.toUTCString()

result.send(date + "")

If you want to return the datetime in specific format, you can do it like this:

// Options for date and time formatting
const options = {
    weekday: 'long',
    year: 'numeric',
    month: 'long',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: true
}

const date = (new Date()).toLocaleString("en-US", options)

This will return the date and time in format: “Tuesday, 2 July, 2024 at 05:11:05 pm”.

Check this tutorial if you want to convert UTC to local timezone in Python.

How to free up space in Mac

In this article, we will show you how you can free up some space in your Mac. If you are running low on space, this is for you.

My Mac was running on 5-6 GB and it keeps getting lower as I work more. So I did the following actions and now my Mac has 37 GB of free space.

1. Goto “home”.

2. Enable hidden files by pressing Command + shift + dot

3. If you do not do iOS development, then it is safe to remove the “.cocoapods” folder.

4. After that, you need to check each folder and see if there is any cache folder in it. You can safely remove all cache folders inside each folder.

4. Then you need to go to “Library”.

5. Remove the “Caches” folder.

6. When you uninstall an app, its files remain there in the “Library” folder. So check all the apps/software that you have uninstalled or no longer use, and delete their folders too.

If you follow the above steps, it will free up a lot of space in your Mac.

Check if time is passed – Python

In this tutorial, you will learn how to check if the time is passed in Python.

First, we will get the future time in UTC. In order to get this, first we will get the current time in UTC.

Then we will add 24 hours in it.

After that, we will get time_struct object from it. This will be used to get the Unix timestamp.

Then we will the Unix timestamp using the time_struct object.

Same can be done for getting the current time in UTC but without adding 24 hours in it.

delta is the difference between future Unix timestamp and current one.

Then we will convert the seconds into minutes by dividing it to 60 since each minute has 60 seconds.

And again dividing that to 60 since each hour has 60 minutes. This will return the number of hours since the time is passed.

Finally, we will check if the delta is less than or equal to zero. If it is, it means that the time is passed. If not, it means that the time is not passed yet.

from datetime import datetime, timezone, timedelta
import time

future_time = datetime.now(timezone.utc)		# current datetime in UTC
future_time = future_time + timedelta(hours=24)	# current time + 24 hours
future_time = future_time.timetuple()			# instance of time.struct_time
future_time = time.mktime(future_time)			# Unix timestamp

current_time = datetime.now(timezone.utc)		# current datetime in UTC
current_time = current_time.timetuple()			# instance of time.struct_time
current_time = time.mktime(current_time)		# Unix timestamp

delta = future_time - current_time				# difference between future datetime and current datetime (in seconds)
delta = delta / 60 / 60							# convert seconds into hours

if delta <= 0:								   # check if the time is passed
	print("Time passed")
else:
	print("Time not passed")

You can check the real-world example of this in the URL shortener app we created in Python.

Convert UTC to local timezone – Python

Here’s how you can get the date and time in UTC and convert it to user’s local timezone in Python.

from fastapi import FastAPI
from datetime import datetime, timezone as timezone_module
from dateutil import tz

app = FastAPI()

utc = datetime.now(timezone_module.utc)

# Hardcode zones:
from_zone = tz.gettz("UTC")
to_zone = tz.gettz("Asia/Karachi")

# you can get user's local timezone in Javascript using following code:
# Intl.DateTimeFormat().resolvedOptions().timeZone

# Tell the datetime object that it's in UTC time zone since 
# datetime objects are 'naive' by default
utc = utc.replace(tzinfo=from_zone)

# Convert time zone
local = utc.astimezone(to_zone)

# get in readable format
local = local.strftime("%b %d, %Y %H:%M:%S")

print(local)

Comments has been added with each line for explanation. You can check its real-world example in a URL shortener app we created in Python.

How to fix CORS error in FastAPI Python

If you are developing an application and getting CORS error in Python FastAPI, then you can fix it by first importing the CORS middleware from FastAPI module. Then you need to add that middleware in your FastAPI “app” instance. Allow all origins, all credentials, and all methods and headers.

from fastapi import FastAPI

from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()

app.add_middleware(
	CORSMiddleware,
	allow_origins=["*"],
	allow_credentials=True,
	allow_methods=["*"],
	allow_headers=["*"]
)

It will fix CORS error in your Python FastAPI. Learn how to create a URL shortener app in Python.