Real Time News Aggregator with NodeJS and ExpressJS Last Updated : 22 Mar, 2024 Comments Improve Suggest changes Like Article Like Report In this article, we will create a real time news application with the help of NodeJS and ExpressJS. This article consists of several main functionalities. First, we will display the news article. Then we have implemented the search functionality to search news based on the title of the news. Then we get the feature to have sorting by date and we can get news of a specific date. Output Preview: Let us have a look at how the final output will look like. Final OutputPre-requisites:NodeJSNPMExpressJSApproach to create a Real Time News Aggregator:We will make use of NodeJS, ExpressJS, EJS and Tailwind CSS to develop our Real Time News Aggregator Application. In this project we will implement two important features, one is displaying the news article and then we can further explore more about each particular news by clicking on Read more. Project Structure:Project Folder StructureSteps to create the Project:Step 1: Initialize the Project npm init --yesStep 2: Install Dependencies npm install express axios ejs tailwindcss nodemon pathStep 3: Start the server nodemon server.jsUpdated Dependencies:"dependencies": {  "axios": "^1.6.8",  "cors": "^2.8.5",  "ejs": "^3.1.9",  "express": "^4.18.3",  "nodemon": "^3.1.0",  "path": "^0.12.7",  "tailwindcss": "^3.4.1" }Example: The below mentioned code implements Real Time News Aggregator with NodeJS and ExpressJS. HTML <!-- ../Views/index.ejs !--> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>News Aggregator</title> <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/tailwind.min.css" rel="stylesheet" /> </head> <body class="bg-gray-100"> <div class="container mx-auto mt-8 flex flex-col items-center justify-center" > <form action="/search" method="GET" class="flex items-center justify-center mt-4" > <input class="w-64 px-4 py-2 rounded-l-lg border border-gray-300 focus:outline-none focus:border-blue-500" name="search" type="search" placeholder="Search" aria-label="Search" /> <button class="px-4 py-2 bg-red-500 text-white rounded-r-lg hover:bg-red-600" type="submit" > Search </button> </form> <form action="/sort-by-date" method="GET"> <button class="mt-4 px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600" type="submit" > Sort by Date </button> </form> <form action="/news-by-date" method="GET" class="mt-4"> <label for="specific-date" class="block mb-2" >Get News for Specific Date:</label > <input id="specific-date" class="w-64 px-4 py-2 rounded-lg border border-gray-300 focus:outline-none focus:border-blue-500" name="date" type="date" aria-label="Specific Date" /> <button class="px-4 py-2 bg-green-500 text-white rounded-lg hover:bg-green-600" type="submit" > Get News </button> </form> <h1 class="text-3xl font-bold my-4 text-center">Latest News</h1> <div id="news-container" class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4" > <% news.forEach(article => { %> <div class="article border p-4 bg-white rounded-lg shadow-md"> <h2 class="text-lg font-bold mb-2"><%= article.title %></h2> <p class="text-gray-700"><%= article.description %></p> <p class="text-gray-700 article-date"> Published at: <%= article.publishedAt %> </p> <a href="<%= article.url %>" class="text-blue-600 font-semibold mt-2 inline-block" >Read more</a > </div> <% }); %> </div> </div> </body> </html> JavaScript // server.js const express = require("express"); const path = require("path"); const axios = require("axios"); const app = express(); app.set("views", path.join(__dirname, "views")); app.set("view engine", "ejs"); app.get("/", async (req, res) => { try { const response = await axios.get( "https://newsapi.org/v2/top-headlines?country=in&apiKey=679b913ddb014617bcc93a0bb89ee1ee" ); const data = response.data; res.render("index", { news: data.articles }); } catch (error) { console.error("Error fetching news:", error); res.status(500).send("Error fetching news. Please try again later."); } }); app.get("/search", async (req, res) => { try { const searchTerm = req.query.search; const response = await axios.get( `https://newsapi.org/v2/everything?q=${searchTerm}&apiKey=679b913ddb014617bcc93a0bb89ee1ee` ); const data = response.data.articles; const news = data.filter((dataItem) => dataItem.title?.toLowerCase().includes(searchTerm?.toLowerCase())); res.render("index", { news }); } catch (error) { console.error("Error fetching search results:", error); res .status(500) .send("Error fetching search results. Please try again later."); } }); app.get("/sort-by-date", async (req, res) => { try { const response = await axios.get( "https://newsapi.org/v2/top-headlines?country=in&apiKey=679b913ddb014617bcc93a0bb89ee1ee" ); const data = response.data.articles; data.sort((a, b) => new Date(b.publishedAt) - new Date(a.publishedAt)); res.render("index", { news: data }); } catch (error) { console.error("Error sorting articles by date:", error); res.status(500).send("Error sorting articles by date. Please try again later."); } }); app.get("/news-by-date", async (req, res) => { try { const date = req.query.date; const response = await axios.get( `https://newsapi.org/v2/everything?q=*&from=${date}&to=${date}&sortBy=popularity&apiKey=679b913ddb014617bcc93a0bb89ee1ee` ); const data = response.data.articles; res.render("index", { news: data }); } catch (error) { console.error("Error fetching news by date:", error); res.status(500).send("Error fetching news by date. Please try again later."); } }); const PORT = process.env.PORT || 3000; app.listen(PORT, () => { console.log(`Server is running on http://localhost:${PORT}`); }); Output: Comment More infoAdvertise with us Next Article Real-Time Auction Platform using Node and Express.js K krishna693rahul Follow Improve Article Tags : Project Web Technologies Node.js Express.js Dev Scripter Web Development Projects Dev Scripter 2024 Node.js - Projects +4 More Similar Reads AI and Machine LearningAI Whatsapp Bot using NodeJS, Whatsapp-WebJS And Gemini AIThis WhatsApp bot is powered by Gemini AI API, where you can chat with this AI bot and get the desired result from the Gemini AI model. This bot can be used in groups or personal chats and only needs to be authenticated using the mobile WhatsApp app. Output Preview: Let us have a look at how the fin 4 min read AI-Powered Chatbot Platform with Node and Express.jsAn AI Powered Chatbot using NodeJS and ExpressJS can be created using the free OpenAI's API Key that is provided for every user login. This article covers a basic syntax of how we can use ES6 (EcmaScript Version 6) to implement the functionalities of Node.js and Express.js including the use of REST 4 min read Book Recommendation System using Node and Express.jsThe Book Recommendation System aims to enhance the user's reading experience by suggesting books tailored to their interests and preferences. Leveraging the power of machine learning and natural language processing, the system will analyze user inputs and recommend relevant books from a database. In 4 min read Movie Recommendation System with Node and Express.jsBuilding a movie recommendation system with Node and Express will help you create personalized suggestions and recommendations according to the genre you selected. To generate the recommendation OpenAI API is used. In this article, you will see the step-wise guide to build a Movie recommendation sys 3 min read Web and API DevelopmentHow to build Node.js Blog API ?In this article, we are going to create a blog API using Node.js. A Blog API is an API by which users can fetch blogs, write blogs to the server, delete blogs, and even filter blogs with various parameters.Functionalities:Fetch BlogsCreate BlogsDelete BlogsFilter BlogsApproach: In this project, we w 4 min read RESTful Blogging API with Node and Express.jsBlogs Websites have become very popular nowadays for sharing your thoughts among the users over internet. In this article, you will be guided through creating a Restful API for the Blogging website with the help of Node, Express, and MongoDB.Prerequisites:Node JS & NPMExpress JSMongoDBApproach t 5 min read Build a Social Media REST API Using Node.js: A Complete GuideDevelopers build an API(Application Programming Interface) that allows other systems to interact with their Applicationâs functionalities and data. In simple words, API is a set of protocols, rules, and tools that allow different software applications to access allowed functionalities, and data and 15+ min read Finance and BudgetingBudget Tracking App with Node.js and Express.jsIn this article, weâll walk through the step-by-step process of creating a Budget Tracking App with Node.js and Express.js. This application will provide users with the ability to track their income, expenses, and budgets. It will allow users to add, delete, and view their income and expenses, as we 15 min read Razorpay Payment Integration using Node.jsPayment gateway is a technology that provides online solutions for money-related transactions, it can be thought of as a middle channel for e-commerce or any online business, which can be used to make payments and receive payments for any purpose.Sample Problem Statement: This is a simple HTML page 14 min read Communication and Social PlatformsHow to Create a Chat App Using socket.io in NodeJS?Socket.io is a JavaScript library that enables real-time, bidirectional, event-based communication between the client and server. It works on top of WebSocket but provides additional features like automatic reconnection, broadcasting, and fallback options.What We Are Going to Create?In this article, 5 min read How to make a video call app in node.js ?For making a video call app, It is required that each and every client send their video and audio stream to all the other clients. So for this purpose we are using Peer.js and for the communication between the clients and the server we are using WebSocket i.e. Socket.io. Prerequisite: 1. Node.js: It 5 min read Health and MedicalHealth Tracker App Backend Using Node and Express.jsA Health Tracker App is a platform that allows users to log and monitor various data of their health and fitness. In this article, we are going to develop a Health Tracker App with Node.js and Express.js. that allows users to track their health-related activities such as exercise, meals, water intak 4 min read Hospital Appointment System using ExpressHospital Appointment System project using Express and MongoDB contains various endpoints that will help to manage hospital appointments. In this project, there is an appointment endpoint for user management and appointment management. API will be able to register users, authenticate users, book appo 12 min read Covid-19 cases update using Cheerio LibraryIn this article we are going to learn about that how can we get the common information from the covid website i.e Total Cases, Recovered, and Deaths using the concept of scraping with help of JavaScript Library. Library Requirements and installation: There are two libraries that are required to scra 3 min read Management SystemsCustomer Relationship Management (CRM) System with Node.js and Express.jsCRM systems are important tools for businesses to manage their customer interactions, both with existing and potential clients. In this article, we will demonstrate how to create a CRM system using Node.js and Express. We will cover the key functionalities, prerequisites, approach, and steps require 15+ min read Library Management Application BackendLibrary Management System backend using Express and MongoDB contains various endpoints that will help to manage library users and work with library data. The application will provide an endpoint for user management. API will be able to register users, authenticate users, borrow books, return books, 10 min read How to Build Library Management System Using NodeJS?A Library Management System is an essential application for managing books, users, and transactions in a library. It involves adding, removing, updating, and viewing books and managing users. In this article, we will walk through how to build a simple Library Management System using NodeJS.What We A 6 min read Student Management System using Express.js and EJS Templating EngineIn this article, we build a student management student which will have features like adding students to a record, removing students, and updating students. We will be using popular web tools NodeJS, Express JS, and MongoDB for the backend. We will use HTML, CSS, and JavaScript for the front end. We' 5 min read Subscription Management System with NodeJS and ExpressJSIn this article, weâll walk through the step-by-step process of creating a Subscription Management System with NodeJS and ExpressJS. This application will provide users with the ability to subscribe to various plans, manage their subscriptions, and include features like user authentication and autho 5 min read Building a Toll Road Management System using Node.jsIn this article, we are going to build a simple Toll Road Management System using Node.js, where the data will be stored in a local MongoDB database.Problem Statement: In a toll tax plaza, it is difficult to record all the transactions and store them in a single place, along with that, if required, 15+ min read How to Build User Management System Using NodeJS?A User Management System is an essential application for handling user accounts and information. It involves creating, reading, updating, and deleting user accounts, also known as CRUD operations. In this article, we will walk through how to build a simple User Management System using NodeJS.What We 6 min read User Management System BackendUser Management System Backend includes numerous endpoints for performing user-dealing tasks. The backend could be constructed with the use of NodeJS and MongoDB with ExpressJS . The software will offer an endpoint for consumer management. API will be capable of registering, authenticating, and cont 4 min read File and Document HandlingBuild a document generator with Express using REST APIIn the digital age, the need for dynamic and automated document generation has become increasingly prevalent. Whether you're creating reports, invoices, or any other type of document, having a reliable system in place can streamline your workflow. In this article, we'll explore how to build a Docume 2 min read DOCX to PDF Converter using ExpressIn this article, we are going to create a Document Conversion Application that converts DOCX to PDF. We will follow step by step approach to do it. We also make use of third-party APIs.Prerequisites:Express JS multernpm Preview of the final output: Let us have a look at how the final output will loo 4 min read How to Send Email using NodeJS?Sending emails programmatically is a common requirement in many applications, especially for user notifications, order confirmations, password resets, and newsletters. In this article, we will learn how to build a simple email-sending system using NodeJS. We will use Nodemailer, a popular module for 5 min read File Sharing Platform with Node.js and Express.jsIn today's digital age, the need for efficient File sharing platforms has become increasingly prevalent. Whether it's sharing documents for collaboration or distributing media files, having a reliable solution can greatly enhance productivity and convenience. In this article, we'll explore how to cr 4 min read React Single File Upload with Multer and Express.jsWhen we want to add functionality for uploading or deleting files, file storage becomes crucial, whether it's for website or personal use. The File Storage project using Express aims to develop a web application that provides users with a secure and efficient way to store and manage their files onli 5 min read Entertainment and MediaMusic Playlist Manager with Node.js and Express.jsIn this article, weâll walk through the step-by-step process of creating a Music Playlist Manager with NodeJS and ExpressJS. This application will provide users with the ability to register, log in, create playlists, add tracks to playlists, update playlists, delete playlists, and manage their user 14 min read Sports Score Tracker with NodeJS and ExpressJSIn sports, real-time updates and scores are very important for fans so that they can stay engaged and informed. In this tutorial, we'll explore how to build a Sports Score Tracker using Node.js and Express.js. Preview Image: Preview lookPrerequisitesJavaScriptNode.jsnpmExpress.jsWorking with APIsApp 4 min read Task and Project ManagementTask Management System using Node and Express.jsTask Management System is one of the most important tools when you want to organize your tasks. NodeJS and ExpressJS are used in this article to create a REST API for performing all CRUD operations on task. It has two models User and Task. ReactJS and Tailwind CSS are used to create a frontend inter 15+ min read Task Manager App using Express, React and GraphQL.The Task Manager app tool is designed to simplify task management with CRUD operation: creation, deletion, and modification of tasks. Users can easily generate new tasks, remove completed ones, and update task details. In this step-by-step tutorial, you will learn the process of building a Basic Tas 6 min read Simple Task Manager CLI Using NodeJSA Task Manager is a very useful tool to keep track of your tasks, whether it's for personal use or a work-related project. In this article, we will learn how to build a Simple Task Manager CLI (Command Line Interface) application using Node.js.What We Are Going to Create?We will build a CLI task man 5 min read Task Scheduling App with Node and Express.jsTask Scheduling app is an app that can be used to create, update, delete, and view all the tasks created. It is implemented using NodeJS and ExpressJS. The scheduler allows users to add tasks in the cache of the current session, once the app is reloaded the data gets deleted. This can be scaled usin 4 min read Todo List CLI application using Node.jsCLI is a very powerful tool for developers. We will be learning how to create a simple Todo List application for command line. We have seen TodoList as a beginner project in web development and android development but a CLI app is something we don't often hear about.Pre-requisites:A recent version o 13 min read Real-Time ApplicationsReal Time News Aggregator with NodeJS and ExpressJSIn this article, we will create a real time news application with the help of NodeJS and ExpressJS. This article consists of several main functionalities. First, we will display the news article. Then we have implemented the search functionality to search news based on the title of the news. Then we 4 min read Real-Time Auction Platform using Node and Express.jsThe project is a Real-Time Auction Platform developed using Node.js Express.js and MongoDB database for storing details where users can browse different categories of products, view ongoing auctions, bid on items, and manage their accounts. The platform also allows sellers to list their products for 12 min read Real-Time Polling App with Node and ReactIn this article, weâll walk through the step-by-step process of creating a Real-Time Polling App using NodeJS, ExpressJS, and socket.io. This project will showcase how to set up a web application where users can perform real-time polling.Preview of final output: Let us have a look at how the final a 5 min read Like