// npm install fsconst fs =require("fs")// npm install ejsapp.set("view engine", "ejs")// npm install express-formidableconst expressFormidable =require("express-formidable")app.use(expressFormidable())app.post("/upload", function (request, result) {// get input name="file" from client sideconst file = request.files.file// set file path in MongoDB GriDFS// this will be saved as "filename" in "fs.files" collectionconst filePath = (newDate().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.
fs.files
This will save all uploaded files.
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.
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", asyncfunction (request, result) {// get file name from URLconst filename = request.params.filename// get file from GridFS bucketconst files =await bucket.find({ filename: filename }) .toArray()// return error if file not foundif (!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.
Then you need to create an API in your Node JS file.
// const ObjectId = mongodb.ObjectIdapp.post("/files/del", asyncfunction (request, result) {// get ID from dataconst _id = request.fields._id// delete file from bucketawait 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.
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.
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.
✅ Compatible with almost every shared/dedicated/VPS hosting.
✅ Free support.
New features:
✅ Optimized sending bulk emails.
Files included:
.php
.css
.js
Tech stack:
PHP +7.0
MySQL +5.0
Bootstrap 4
Vue JS 3
Recruiter can post a job
Recruiter posted jobs
Change status of applicant
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 Detail
They can view the job details by clicking the job title.
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.
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 formattingconst options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric', hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: true}const date = (newDate()).toLocaleString("en-US", options)
This will return the date and time in format: “Tuesday, 2 July, 2024 at 05:11:05 pm”.
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.
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.
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.
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.