-->

ABOUT US

Our development agency is committed to providing you the best service.

OUR TEAM

The awesome people behind our brand ... and their life motto.

  • Kumar Atul Jaiswal

    Ethical Hacker

    Hacking is a Speed of Innovation And Technology with Romance.

  • Kumar Atul Jaiswal

    CEO Of Hacking Truth

    Loopholes are every major Security,Just need to Understand it well.

  • Kumar Atul Jaiswal

    Web Developer

    Techonology is the best way to Change Everything, like Mindset Goal.

OUR SKILLS

We pride ourselves with strong, flexible and top notch skills.

Marketing

Development 90%
Design 80%
Marketing 70%

Websites

Development 90%
Design 80%
Marketing 70%

PR

Development 90%
Design 80%
Marketing 70%

ACHIEVEMENTS

We help our clients integrate, analyze, and use their data to improve their business.

150

GREAT PROJECTS

300

HAPPY CLIENTS

650

COFFEES DRUNK

1568

FACEBOOK LIKES

STRATEGY & CREATIVITY

Phasellus iaculis dolor nec urna nullam. Vivamus mattis blandit porttitor nullam.

PORTFOLIO

We pride ourselves on bringing a fresh perspective and effective marketing to each project.

Showing posts with label Web Developing. Show all posts
Showing posts with label Web Developing. Show all posts
  • Difference between Yarn and Npm

     

    Difference between Yarn and Npm

     

     

    Yarn and npm (Node Package Manager) are package managers for JavaScript. They help developers manage project dependencies (libraries and tools that a project needs to function). Here are some key differences between Yarn and npm:

     

    Yarn

     

    Speed and Performance


    # Yarn: Known for its faster performance compared to older versions of npm. Yarn achieves this speed through parallelized operations. It downloads packages in parallel and uses a global cache to reduce the need for repeated downloads.

    # npm: While older versions of npm were slower, the newer versions (npm 5 and above) have improved significantly in terms of speed and performance. npm also introduced a caching mechanism, but its operations are not as parallelized as Yarn’s.

     

    2. Lock Files


     # Yarn: Uses a `yarn.lock` file to lock the versions of the packages that are installed. This ensures that the same versions of dependencies are installed every time the project is built, leading to more consistent builds. 

     


     

     

    # npm: Uses a `package-lock.json` file, which serves a similar purpose as Yarn’s `yarn.lock`. It was introduced in npm version 5 to improve the reliability of builds by ensuring that the exact same dependencies are installed for every build.

     

     


     

     

     3. Installation of Dependencies


     # Yarn: Installs dependencies from the top-level down, which can lead to better performance and fewer conflicts.
     

    # npm: Traditionally, npm installed dependencies recursively, which could lead to larger `node_modules` directories and more conflicts. Recent versions of npm (npm 7+) use a similar approach to Yarn, flattening the `node_modules` hierarchy.

     

    4. Security
     

    # Yarn: Has a built-in feature to check for vulnerabilities in dependencies using the `yarn audit` command.

    # npm: Also provides a similar feature with the `npm audit` command. In addition, npm automatically checks for vulnerabilities during installation and provides a summary.
     

     

    5. Community and Ecosystem
     

    # Yarn: Gained popularity quickly after its release and has a strong community. It is backed by Facebook, which contributed to its initial popularity.

    # npm: Has been around longer and has a larger user base and community. It is maintained by GitHub (Microsoft).

     

     


    Disclaimer



    All tutorials are for informational and educational purposes only and have been made using our own routers, servers, websites and other vulnerable free resources. we do not contain any illegal activity. We believe that ethical hacking, information security and cyber security should be familiar subjects to anyone using digital information and computers. Hacking Truth is against misuse of the information and we strongly suggest against it. Please regard the word hacking as ethical hacking or penetration testing every time this word is used. We do not promote, encourage, support or excite any illegal activity or hacking.

     

     

     

     

  • "Unlocking the Power of APIs: How to Obtain a Dropdown Menu and Store it in a Database"

     

    "Unlocking the Power of APIs: How to Obtain a Dropdown Menu and Store it in a Database"


    "Unlocking the Power of APIs: How to Obtain a Dropdown Menu and Store it in a Database"


    In the fast-paced and interconnected digital landscape, Application Programming Interfaces (APIs) have emerged as the driving force behind seamless connectivity, collaboration, and innovation. APIs act as bridges between different software systems, allowing them to communicate, share data, and perform functions that enhance the overall user experience. As businesses strive for efficiency and adaptability, unlocking the power of APIs has become a strategic imperative.


    How to Obtain a Dropdown Menu and Store it in a Database


    Here, we will start how to gain dropdown menu via API nodejs express and when user choose any menu then data will store in Mongodb Database. In nodejs there is potential to make a API with the help of any End-point like you know about API how is look like !! right.

    Let's define first how is Actually Nodejs, expressjs, after that we will see about mongodb and how can we store it. Okay!!!

    Nodejs is a powerful, open-source, server-side runtime environment that allows developers to build scalable and high-performance network applications. It is built on the chrome V8 javascript runtime and uses an event-driven, such as web servers, chat applications, and online gaming platforms.


    Here are key aspects of Node.js:

    JavaScript Runtime:


    Node.js allows developers to use JavaScript for server-side scripting. This unifies the language used for both client-side and server-side development, which can streamline the development process.

     

    What is MongoDB

     

    MongoDB is a popular open-source NoSQL (non-relational) database management system. NoSQL means no structure like it is look like an object while in SQL it is a structure query language like SELECT CustomerName, City FROM Customers; (The SELECT statement is used to select data from a database.) But NoSQL database is useless...NOT completely because of whenever we want add extra column in database then it is possible through NoSQL MongoDB.   

     

    MongoDB installation - CLICK HERE

    MongoDB Basic Command - CLICK HERE

    About MongoDB vs SQL - CLICK HERE

    CRUD in MongoDB - CLICK HERE

     

     



    Object Like - 

     

     

    {
      "_id": {
        "$oid": "659ad46e0382148123c82841"
      },
      "name": "moto G60",
      "brand": "motorola",
      "price": 16500,
      "category": "mobile"
    }
    
    
    

     

     


    MongoDB is a type of database that helps store and manage large amounts of data in a flexible and scalable way. Unlike SQL, MongoDB doesn't require a fixed structure for the data, allowing you to store information in a more versatile format.


    • MongoDB is a NoSQL database.
    • The data stored in a collection
    • Collection don't have row and columns
    • Data is stored in the form of object.


    Reactjs Application


    Here, we will start from reactjs application and create a new project, after that in src folder create a new folder like components and inside this components folder create a file called as Dropdown.jsx. In App.jsx file, we need to add Dropdown.jsx file add to the app.jsx file.

    Now its coding time


    Dropdown.jsx



    import React from 'react'
    
    function Dropdown() {
      
    
      return (
        
        <div>
        <p>Dropdown</p>
        </div>
      
      );
    }
    
    export default Dropdown;
    
    
    



    Now create a three useState();



    import React, { useEffect, useState } from "react";
    
    function Dropdown() {
    
      const [designation, setDesignation] = useState();
      const [dropdownData, setDropdowndata] = useState([]);
      const [selectedOption, setSelectedOption] = useState("");
    
    
      return (
        
        <div>
        <p>Dropdown</p>
        </div>
      
      );
    }
    
    export default Dropdown;
    
    



    now this some we are trying to create a interface of dropdown menu and submit button



    import React, { useEffect, useState } from "react";
    
    function Dropdown() {
    
      const [designation, setDesignation] = useState();
      const [dropdownData, setDropdowndata] = useState([]);
      const [selectedOption, setSelectedOption] = useState("");
    
    
      return (
        
        <div class="grid grid-cols-1  ml-20 mt-[50px] mr-20  ">
            <div class="flex flex-wrap -mx-3 mb-6">
              <div class="w-full md:w-1/2 px-3 mb-6 md:mb-0">
                <div class="w-full md:w-1/2 px-3 mb-6 md:mb-0">
                  <label
                    class="block uppercase tracking-wide text-gray-700 text-xs font-bold mb-2"
                    for="Designation"
                  >
                    Designation
                  </label>
    
                  <select
                    value={selectedOption}
                    onChange={(e) => setSelectedOption(e.target.value)}
                    className="dropdown-button  w-full bg-white p-2 border text-xs/[12px] py-3 px-4 "
                  >
                    <option
                      value={designation}
                      onChange={(e) => setDesignation(e.target.value)}
                      disabled
                    >
                      Select an option
                    </option>
                    {dropdownData.map((option) => (
                      <option key={option} value={option}>
                        {option}
                      </option>
                    ))}
                  </select>
    
                  {selectedOption && <p>You selected: {selectedOption}</p>}
                </div>
    
                <button
                  className="bg-blue-600 text-white pt-2 pb-2 pr-3 pl-3 mt-3 ml-3"
                  onClick={handleSubmit}
                >
                  Add Employee
                </button>
              </div>
            </div>
          </div>
      );
    }
    
    export default Dropdown;
    
    



    Handle the data but this time check our code very carefully becuase of we have to used API and fetch the Dropdown menu from API nodejs. okay!!


    complete reactjs application



    import axios from "axios";
    import React, { useEffect, useState } from "react";
    
    function Dropdown() {
      const [designation, setDesignation] = useState();
    
      const [dropdownData, setDropdowndata] = useState([]);
      const [selectedOption, setSelectedOption] = useState("");
      
    
      const handleSubmit = async () => {
        try {
          const response = await axios.post(
            "http://localhost:8000/createEmployee",
            {
              designation: selectedOption,
            }
          );
          if (response.status === 200) {
            console.log("Status is good");
          }
          console.log(response);
          console.log(response.data);
          setDesignation('');
        } catch (error) {
          console.log("Error adding employeeData", error.message);
        }
      };
    
      useEffect(() => {
        const fetchData = async () => {
          try {
            const response = await axios.get("http://localhost:8000/api/dropdown");
            setDropdowndata(response.data);
          } catch (error) {
            console.log("Error fetching dropdown data: ", error.message);
          }
        };
    
        fetchData();
      }, []);
    
      return (
        <div>
          <div class="grid grid-cols-1  ml-20 mt-[50px] mr-20  ">
            <div class="flex flex-wrap -mx-3 mb-6">
              <div class="w-full md:w-1/2 px-3 mb-6 md:mb-0">
                <div class="w-full md:w-1/2 px-3 mb-6 md:mb-0">
                  <label
                    class="block uppercase tracking-wide text-gray-700 text-xs font-bold mb-2"
                    for="Designation"
                  >
                    Designation
                  </label>
    
                  <select
                    value={selectedOption}
                    onChange={(e) => setSelectedOption(e.target.value)}
                    className="dropdown-button  w-full bg-white p-2 border text-xs/[12px] py-3 px-4 "
                  >
                    <option
                      value={designation}
                      onChange={(e) => setDesignation(e.target.value)}
                      disabled
                    >
                      Select an option
                    </option>
                    {dropdownData.map((option) => (
                      <option key={option} value={option}>
                        {option}
                      </option>
                    ))}
                  </select>
    
                  {selectedOption && <p>You selected: {selectedOption}</p>}
                </div>
    
                <button
                  className="bg-blue-600 text-white pt-2 pb-2 pr-3 pl-3 mt-3 ml-3"
                  onClick={handleSubmit}
                >
                  Add Employee
                </button>
              </div>
            </div>
          </div>
        </div>
      );
    }
    
    export default Dropdown;
    
    



    const response = await axios.post("http://localhost:8000/createEmployee");
    const response = await axios.get("http://localhost:8000/api/dropdown");



    NOTE :- You can add these lines only when you have created the API in NodeJS.

    in App.jsx file, we will import our dropdown.jsx file.



    "Unlocking the Power of APIs: How to Obtain a Dropdown Menu and Store it in a Database"


    finally run this application. By this command npm run dev




    "Unlocking the Power of APIs: How to Obtain a Dropdown Menu and Store it in a Database"


    NOTE :- At this time please ignore Dropdown data as we have not created the API yet.



    MongodDB Database


    Why we are building mongodb database and collection(table) because we will need conection URL to connect in nodejs and also we will need database name and collection name.


    after installing mongodb compass in your system simply open it and copy the url and click connect button.

     

    "Unlocking the Power of APIs: How to Obtain a Dropdown Menu and Store it in a Database"

     



    After click on button then we have some command for you, by the use this command you can simply create database and its collection .


    - show dbs   (database check)
    - use optionmenu (create db)
    - db.createCollection('employeedatas')  (create table)
    - show collections (check table - by default we don't any data because of not yet wr create a any data)



    "Unlocking the Power of APIs: How to Obtain a Dropdown Menu and Store it in a Database"



    Nodejs - Expressjs API


    Here, first we need to install to some pkg in server side application because of we need to some pkg for make API purpose.

    npm init
    npm i express
    npm i mongodb  (
    mongodb connection)
    npm i cors
    npm i nodemon -g (
    for run our server side application, -g means globaly)
    npm i mongoose  (it is driver for connection of nodejs and mongodb)


    Create a new folder called as server outside of reactjs application project folder and open cmd prompt in server directory and install one by one pkg.


    "Unlocking the Power of APIs: How to Obtain a Dropdown Menu and Store it in a Database"

    "Unlocking the Power of APIs: How to Obtain a Dropdown Menu and Store it in a Database"


    "Unlocking the Power of APIs: How to Obtain a Dropdown Menu and Store it in a Database"

    "Unlocking the Power of APIs: How to Obtain a Dropdown Menu and Store it in a Database"



    server.js


    First, we will create a folder called as mongodb and inside this folder we will create a file called as config.js



    const mongoose = require('mongoose')
    mongoose.connect("mongodb://127.0.0.1:27017/optionmenu")
    
    
    


    optionmenu - it is our database name.

    mongodb://127.0.0.1:27017/ - it is our connection url when open mongodb you get it.





    const express = require('express');
    
    const cors = require('cors');
    
    const app = express();
    app.use(cors());
    app.use(express.json());
    
    
    const DropDownOptions = ['HR', 'Manager', 'Employee'];
    
    
    app.get('/api/dropdown', (req, resp) => {
        resp.json(DropDownOptions)
    })
    
    app.listen(8000, () => {
        console.log('Server is running on port 8000');
    })
    
    
    



    Then simply run nodemon server.js file in vs code terminal.

    Now we will check in our postman for dropdown data is coming or not.



    "Unlocking the Power of APIs: How to Obtain a Dropdown Menu and Store it in a Database"



    Yupee!! We got it.


    again we will create a new API for uploading the data when user select dropdown menu options and store it. 

     

    but before creating a new API, lets make schemas and model. For this first create a new folder called as schema and inside this folder create a file employee.js.

     

     

    "Unlocking the Power of APIs: How to Obtain a Dropdown Menu and Store it in a Database"

     

    1. importing the mongoose.

    This line imports the Mongoose library, which is a popular ODM (Object Data Modeling) library for MongoDB and Node.js. It provides a way to define schemas, interact with the MongoDB database, and perform various operations.

    const mongoose = require('mongoose');

     

    2. Defining a Mongoose Schema:

     

     const employeeSchema = new mongoose.Schema 

    ({

    designation: String,

    })

     

    This code creates a Mongoose schema for the "employeeData" collection. The schema specifies that documents in this collection should have a field named "designation" of type String. This is a basic example, and in a real-world scenario, you would include more fields and specify their types.

     


     3. Exporting the Mongoose Model


    module.exports = mongoose.model('employeeData', employeeSchema)



    The code exports a Mongoose model based on the defined schema. The mongoose.model function takes two arguments:

    The first argument ('employeeData') is the name of the MongoDB collection. This name is case-sensitive and is typically given in the singular form.

    The second argument (employeeSchema) is the schema definition. By exporting this model, you can use it in other parts of your application to interact with the MongoDB collection named "employeeData."


     



    app.post('/createEmployee', async (req, resp) => {
        try {
            const {
                designation
            } = req.body;
            const newEmployee = new employee({
           designation
            });
            await newEmployee.save();
    
            resp.status(200).json({message: 'Employee created successfully'})
        } catch(error){
            resp.status(500).json({message: 'Internal Server Error'});
        }
    });
    



    Server.js



    const express = require('express');
    require('./mongodb/config')
    const employee = require('./schema/employee')
    
    const cors = require('cors');
    
    const app = express();
    app.use(cors());
    app.use(express.json());
    
    app.post('/createEmployee', async (req, resp) => {
        try {
            const {
                designation
            } = req.body;
            const newEmployee = new employee({
           designation
            });
            await newEmployee.save();
    
            resp.status(200).json({message: 'Employee created successfully'})
        } catch(error){
            resp.status(500).json({message: 'Inernal Server Error'});
        }
    });
    
    
    const DropDownOptions = ['HR', 'Manager', 'Employee'];
    
    
    app.get('/api/dropdown', (req, resp) => {
        resp.json(DropDownOptions)
    })
    
    app.listen(8000, () => {
        console.log('Server is running on port 8000');
    })
    
    
    



    Finally our time is come. 

     


    "Unlocking the Power of APIs: How to Obtain a Dropdown Menu and Store it in a Database"

    "Unlocking the Power of APIs: How to Obtain a Dropdown Menu and Store it in a Database"





    Disclaimer



    All tutorials are for informational and educational purposes only and have been made using our own routers, servers, websites and other vulnerable free resources. we do not contain any illegal activity. We believe that ethical hacking, information security and cyber security should be familiar subjects to anyone using digital information and computers. Hacking Truth is against misuse of the information and we strongly suggest against it. Please regard the word hacking as ethical hacking or penetration testing every time this word is used. We do not promote, encourage, support or excite any illegal activity or hacking.

     

     

  • Events and Event Emitter in nodejs

     

    Events and Event Emitter in nodejs

     

     

    Events and Event Emitter in nodejs



    This blog we have seen mongodb basic and how is it work with installation and after installation, we have already seen mongodb basic, CRUD operation, connect mongodb with nodejs, read, update, delete, POST, GET API etc. we should not face any problem while making Database, collection(table) and using the data in nodejs even whenever we will make API. Read data from mongodb in nodejs



    • # What is Mongoose
    • # Install Mongoose
    • # What is Events and Event Emitter
    • # Make an event and call it


     

    Now in this blog  we will use mongoose. There is an npm package to connect nodes to mongodb. Mongoose is a MongoDB object modeling tool designed to work in an asynchronous environment. They created mongoose by improving mongodb, with the help of which you can create schemas and models of mongoose's movements.

    Suppose that there are 4 fields in our database (like name, brand, price, category) and the user wants to add a 5th field also (like color) but we want to add only 4 fields, for this we create schemas.

    Here you can also define TYPE in schemas like price type is numeric but if any user wants to use quotes (" " ' ') then we can stop the user for this.

    in sort we can apply validation in mongoose but we can't in directly mongodb.

     

     

     What is MongoDB

     

    MongoDB is a popular open-source NoSQL (non-relational) database management system. NoSQL means no structure like it is look like an object while in SQL it is a structure query language like SELECT CustomerName, City FROM Customers; (The SELECT statement is used to select data from a database.) But NoSQL database is useless...NOT completely because of whenever we want add extra column in database then it is possible through NoSQL MongoDB.   

     

    MongoDB installation - CLICK HERE

    MongoDB Basic Command - CLICK HERE

    About MongoDB vs SQL - CLICK HERE

    CRUD in MongoDB - CLICK HERE

     

     



    Object Like - 

     

     

    {
      "_id": {
        "$oid": "659ad46e0382148123c82841"
      },
      "name": "moto G60",
      "brand": "motorola",
      "price": 16500,
      "category": "mobile"
    }
    
    
    

     

     


    MongoDB is a type of database that helps store and manage large amounts of data in a flexible and scalable way. Unlike SQL, MongoDB doesn't require a fixed structure for the data, allowing you to store information in a more versatile format.


    • MongoDB is a NoSQL database.
    • The data stored in a collection
    • Collection don't have row and columns
    • Data is stored in the form of object.




    Install Mongoose


    For this you need to copy this (npm i mongoose) and paste it in project's terminal.

    https://www.npmjs.com/package/mongoose

     

     

     

    Events and Event Emitter in nodejs

     

     

    What is Events and Event Emitter

     

    In nodejs, an event is an action or occurrence that can be observed and responded to . Node.js provides the event emitter pattern as a core module to handle events. The Event emitter is an implementation of the observer pattern allowing objects (event emitter) to emit the named events that cause function objects (listeners) to be called.

     

    OR

     

    if i will use button in HTML and add the onClick event and whenever we click on button and generate the function and get a signal that please call the function and execute the code.

    and the event is that which observes the singal received from the event and works on that pattern.



    Basic Usage:



    To use the Event Emitter, you first create an instance of Event Emitter.

    You can then use the .on(eventName, listener) method to attach a listener function to a specific event.

    The .emit(eventName, ...args) method is used to emit (trigger) an event, and any attached listeners for that event are called.

     

     

    Q) How can we make a button in Node.js ?

     Ans - Through API and use Event Emitter

     

     

    Make an event and call it

     

    First we will make a API and import express and EventEmitter (EventEmitter is inbuilt module in nodejs) so don't need to install in nodejs.



    const express = require('express')
    const EventEmitter = require('events');
    const app = express()
    
    
    app.get("/", (req, resp) => {
        resp.send("Done")
        console.log("API called")
    })
    
    app.listen(8000)
    

     

     

    Events and Event Emitter in nodejs

     

     

    Now we will see when we create so many API then we will check how many hit on particular API.


     

    app.get("/", (req, resp) => {
        resp.send("Home page API")
        console.log("Home page API called")
    })
    
    
    app.get("/search", (req, resp) => {
        resp.send("Search API")
        console.log("Search API called")
    })
    
    
    
    app.get("/update", (req, resp) => {
        resp.send("update page API")
        console.log("update API called")
    })
    
    

     

     

     Now we make a function that means it will keep updating the count of every hit we get on our API in the database.



    const express = require("express");
    const EventEmitter = require("events");
    const app = express();
    
    const event = new EventEmitter();
    //this is object
    
    let count = 0;
    
    event.on("countAPI", () => {
      count++;
      console.log("Event called", count);
    });
    
    //first is the event name - countAPI
    //second is the callback function
    
    
    
    app.get("/", (req, resp) => {
      resp.send("Home page API");
      event.emit("countAPI"); 
    });
    
    app.get("/search", (req, resp) => {
      resp.send("Search API");
      event.emit("countAPI"); 
    });
     
    app.get("/update", (req, resp) => {
      resp.send("update page API");
      event.emit("countAPI");
    });
    
    app.listen(8000);
    
    

     

     

     

    Events and Event Emitter in nodejs

     

     


    Disclaimer



    All tutorials are for informational and educational purposes only and have been made using our own routers, servers, websites and other vulnerable free resources. we do not contain any illegal activity. We believe that ethical hacking, information security and cyber security should be familiar subjects to anyone using digital information and computers. Hacking Truth is against misuse of the information and we strongly suggest against it. Please regard the word hacking as ethical hacking or penetration testing every time this word is used. We do not promote, encourage, support or excite any illegal activity or hacking.

     

     

  • OS module in Nodejs

     

    OS module in Nodejs

     

     

     

    upload the file from nodejs



    This blog we have seen mongodb basic and how is it work with installation and after installation, we have already seen mongodb basic, CRUD operation, connect mongodb with nodejs, read, update, delete, POST, GET API etc. we should not face any problem while making Database, collection(table) and using the data in nodejs even whenever we will make API. Read data from mongodb in nodejs



    • # What is OS module
    • # Important functions of OS module

     

    What is OS Module ?

     

    In Node.js, the 'os' (operating system) module provides a set of methods to interact with the operating system. It allows you to access information about the system's resources, network interfaces, and other related details. Here are some commonly used functionalities provided by the OS module.

     

     

    const os = require("os");
    console.log(os.arch())
    
    

     

    Returns a string identifying the operating system CPU architecture (e.g., 'x64').


     

    OS module in Nodejs

     

     

    const os = require("os");
    console.log(os.freemem()/(1024*1024));
    console.log(os.freemem()/(1024*1024*1024));
    
    

     

    Returns the amount of free system memory in bytes. 


     

    OS module in Nodejs

     

     

     

    const os = require("os");
    
    console.log(os.totalmem()/(1024*1024));
    console.log(os.totalmem()/(1024*1024*1024));
    
    

     

    Returns the total amount of system memory in bytes.

     

     

    OS module in Nodejs

     

     

    const os = require("os");
    
    console.log(os.hostname());
    
    

     

    Returns the host name of the operating system.

     

    OS module in Nodejs

     

     

    const os = require("os");
    
    console.log(os.platform());
    
    

     

     

    Returns a string identifying the operating system platform (e.g., 'darwin', 'win32', 'linux').

     

     

    OS module in Nodejs

     

     

    const os = require("os");
    
    console.log(os.userInfo());
    

     


     

    OS module in Nodejs

     

     


    Disclaimer



    All tutorials are for informational and educational purposes only and have been made using our own routers, servers, websites and other vulnerable free resources. we do not contain any illegal activity. We believe that ethical hacking, information security and cyber security should be familiar subjects to anyone using digital information and computers. Hacking Truth is against misuse of the information and we strongly suggest against it. Please regard the word hacking as ethical hacking or penetration testing every time this word is used. We do not promote, encourage, support or excite any illegal activity or hacking.

     

  • upload the file from nodejs

     

    upload the file from nodejs

     

     

    upload the file from nodejs



    This blog we have seen mongodb basic and how is it work with installation and after installation, we have already seen mongodb basic, CRUD operation, connect mongodb with nodejs, read, update, delete, POST, GET API etc. we should not face any problem while making Database, collection(table) and using the data in nodejs even whenever we will make API. Read data from mongodb in nodejs



    • # What is Mongoose
    • # Install Mongoose
    • # Install Multer npm package
    • # Make Router for upload file


     

    Now in this blog  we will use mongoose. There is an npm package to connect nodes to mongodb. Mongoose is a MongoDB object modeling tool designed to work in an asynchronous environment. They created mongoose by improving mongodb, with the help of which you can create schemas and models of mongoose's movements.

    Suppose that there are 4 fields in our database (like name, brand, price, category) and the user wants to add a 5th field also (like color) but we want to add only 4 fields, for this we create schemas.

    Here you can also define TYPE in schemas like price type is numeric but if any user wants to use quotes (" " ' ') then we can stop the user for this.

    in sort we can apply validation in mongoose but we can't in directly mongodb.

     

     

     What is MongoDB

     

    MongoDB is a popular open-source NoSQL (non-relational) database management system. NoSQL means no structure like it is look like an object while in SQL it is a structure query language like SELECT CustomerName, City FROM Customers; (The SELECT statement is used to select data from a database.) But NoSQL database is useless...NOT completely because of whenever we want add extra column in database then it is possible through NoSQL MongoDB.   

     

    MongoDB installation - CLICK HERE

    MongoDB Basic Command - CLICK HERE

    About MongoDB vs SQL - CLICK HERE

    CRUD in MongoDB - CLICK HERE

     

     



    Object Like - 

     

     

    {
      "_id": {
        "$oid": "659ad46e0382148123c82841"
      },
      "name": "moto G60",
      "brand": "motorola",
      "price": 16500,
      "category": "mobile"
    }
    
    
    

     

     


    MongoDB is a type of database that helps store and manage large amounts of data in a flexible and scalable way. Unlike SQL, MongoDB doesn't require a fixed structure for the data, allowing you to store information in a more versatile format.


    • MongoDB is a NoSQL database.
    • The data stored in a collection
    • Collection don't have row and columns
    • Data is stored in the form of object.




    Install Mongoose


    For this you need to copy this (npm i mongoose) and paste it in project's terminal.

    https://www.npmjs.com/package/mongoose

     

     

    upload the file from nodejs

     

     

     

    Install Multer npm package

     

    First we need to install multer npm package in our project, if you want you can also write the code without this npm package. Let's first install it.

    Simple go this link - CLICK HERE

    CMD for installation - npm i multer

     

     

    Make Router for upload file 

     

    Now we will write code of upload file with the npm package multer but first we will send data POST method and using /upload endpoint and also you can create a folder named as uploads.

     

     

    const express = require('express')
    const multer = require('multer');
    const app = express();
    
    
    app.post("/upload" , (req, resp) => {
        resp.send("File uploaded")
    });
    
    
    app.listen(8000)
    

     

     

     

    upload the file from nodejs

     

     

    const upload = multer({
        storage: multer.diskStorage({
            destination:function(req, file, cb)
            {
                cb(null,'uploads/') //folder to save the files in 
    
            },
            filename:function(req, file, cb)
            {
               // cb(null, file.fieldname + "-" + Date.now() + ".jpg" )
                //if you can extract extension from  file then use this code
                var  ext=file.originalname.split(".");
                if(ext[ext.length-1]==='jpg' || ext[ext.length -1 ] === 'png'){
                    cb(null , file.fieldname+ '-' +Date.now()+"."+ext[ext.length -1]);
                }else{
                    cb(new Error('Error : Only jpg and png are allowed'));
            }
        }
        })
    }).single("user_file");// field name in form data
    

     

     

     

     Let's breakdown the code.




    1) Multer Configuration:

    const upload = multer({
        storage: multer.diskStorage({
            // ... configuration options ...
        })
    }).single("user_file");



    # upload: This variable holds the configured multer middleware. It's set up to handle a single file upload.
    # multer: This is the Multer middleware.
    # storage: Multer's storage option defines how files should be stored. In this case, it uses multer.diskStorage to specify that files should be stored on the disk.


    multer.diskStorage({
        destination: function(req, file, cb) {
            cb(null, 'uploads/');
        },
        filename: function(req, file, cb) {
            // ... filename configuration ...
        }
    })




    destination: A function that determines the destination folder for storing uploaded files. In this example, it's set to 'uploads/'. You need to make sure the 'uploads' directory exists in your project.

    filename: A function that determines the name of the uploaded file. It checks the file extension and appends a timestamp to the original filename if it's a jpg or png file. If the file extension is not allowed, it throws an error.




    3) Error Handling:


    if (ext[ext.length - 1] === 'jpg' || ext[ext.length - 1] === 'png') {
        cb(null, file.fieldname + '-' + Date.now() + '.' + ext[ext.length - 1]);
    } else {
        cb(new Error('Error: Only jpg and png are allowed'));
    }




    This part of the code checks the file extension. If the extension is 'jpg' or 'png', it generates a filename with the original fieldname, a timestamp, and the file extension. If the extension is not allowed, it invokes the callback with an error.


    }).single("user_file");




    The .single("user_file") part specifies that it's expecting a single file upload with the field name "user_file". The field name should match the one used in your HTML form's file input.




     

     Whole Code



    const express = require('express')
    const multer = require('multer');
    const app = express();
    
    
    const upload = multer({
        storage: multer.diskStorage({
            destination:function(req, file, cb)
            {
                cb(null,'uploads/') //folder to save the files in 
    
            },
            filename:function(req, file, cb)
            {
              
                var  ext=file.originalname.split(".");
                if(ext[ext.length-1]==='jpg' || ext[ext.length -1 ] === 'png'){
                    cb(null , file.fieldname+ '-' +Date.now()+"."+ext[ext.length -1]);
                }else{
                    cb(new Error('Error : Only jpg and png are allowed'));
            }
        }
        })
    }).single("user_file");// field name in form data
    
    app.post("/upload", upload , (req, resp) => {
        resp.send("File uploaded")
    });
    
    
    app.listen(8000)
    



    upload the file from nodejs





    Disclaimer



    All tutorials are for informational and educational purposes only and have been made using our own routers, servers, websites and other vulnerable free resources. we do not contain any illegal activity. We believe that ethical hacking, information security and cyber security should be familiar subjects to anyone using digital information and computers. Hacking Truth is against misuse of the information and we strongly suggest against it. Please regard the word hacking as ethical hacking or penetration testing every time this word is used. We do not promote, encourage, support or excite any illegal activity or hacking.

     

  • Search API with multiple filed in nodejs

     


     

     

    Search API with multiple filed in nodejs



    This blog we have seen mongodb basic and how is it work with installation and after installation, we have already seen mongodb basic, CRUD operation, connect mongodb with nodejs, read, update, delete, POST, GET API etc. we should not face any problem while making Database, collection(table) and using the data in nodejs even whenever we will make API. Read data from mongodb in nodejs



    • # What is Mongoose
    • # Install Mongoose
    • # Make Simple GET Route for API
    • # Search with single field
    • # Search with multiple fields
    • # Test API 


     

    Now in this blog  we will use mongoose. There is an npm package to connect nodes to mongodb. Mongoose is a MongoDB object modeling tool designed to work in an asynchronous environment. They created mongoose by improving mongodb, with the help of which you can create schemas and models of mongoose's movements.

    Suppose that there are 4 fields in our database (like name, brand, price, category) and the user wants to add a 5th field also (like color) but we want to add only 4 fields, for this we create schemas.

    Here you can also define TYPE in schemas like price type is numeric but if any user wants to use quotes (" " ' ') then we can stop the user for this.

    in sort we can apply validation in mongoose but we can't in directly mongodb.

     

     

     What is MongoDB

     

    MongoDB is a popular open-source NoSQL (non-relational) database management system. NoSQL means no structure like it is look like an object while in SQL it is a structure query language like SELECT CustomerName, City FROM Customers; (The SELECT statement is used to select data from a database.) But NoSQL database is useless...NOT completely because of whenever we want add extra column in database then it is possible through NoSQL MongoDB.   

     

    MongoDB installation - CLICK HERE

    MongoDB Basic Command - CLICK HERE

    About MongoDB vs SQL - CLICK HERE

    CRUD in MongoDB - CLICK HERE

     

     



    Object Like - 

     

     

    {
      "_id": {
        "$oid": "659ad46e0382148123c82841"
      },
      "name": "moto G60",
      "brand": "motorola",
      "price": 16500,
      "category": "mobile"
    }
    
    
    

     

     


    MongoDB is a type of database that helps store and manage large amounts of data in a flexible and scalable way. Unlike SQL, MongoDB doesn't require a fixed structure for the data, allowing you to store information in a more versatile format.


    • MongoDB is a NoSQL database.
    • The data stored in a collection
    • Collection don't have row and columns
    • Data is stored in the form of object.




    Install Mongoose


    For this you need to copy this (npm i mongoose) and paste it in project's terminal.

    https://www.npmjs.com/package/mongoose

     


     


     

    Make Simple GET Route for API

     

    Here, we simple import express.js, configuration of mongodb file and schema file and express.json for converting into json format after getting output after that we create a /search route with /:key as a parameter. Then,  Product is our schema file and find method for all the data gaining from the mongodb.

     

     

    const express = require('express');
    require('./config')
    const Product = require('./product')
    const app = express();
    
    app.use(express.json());
    
    
    app.get('/search/:key', async (req, resp) => {
       console.log(req.params.key);
       let data = await Product.find()
       resp.send(data)
       //resp.send('Done')
    })
    
    
    
    app.listen(8000)
    

     

     

    Run with nodemon index.js and after that we hit the request from postman.

     

     


     

     

    Then we will search single data from single search 

     

     

    app.get('/search/:key', async (req, resp) => {
       console.log(req.params.key);
       let data = await Product.find(
          {
             "$or": [
                   { "name": {$regex: req.params.key}}
                   ]
        }
       )
       resp.send(data)
       //resp.send('Done')
    })
    

     

     

     

    This code represents a route handler for an Express.js application. It defines an HTTP GET endpoint at the path '/search/:key'. The endpoint is designed to handle requests with a dynamic parameter ':key', which represents the search key or term.



    Database Query Using Mongoose:


    let data = await Product.find({ "$or": [{ "name": {$regex: req.params.key}}] });

    This line uses the Mongoose library to query the MongoDB database. It searches for documents in the 'Product' collection where the 'name' field matches the provided search key using a case-insensitive regular expression.

     

     

     

    Search API with multiple filed in nodejs

     

     

    Here's, only we are searched single search but after that we will create multiple search that's mean user search with value according to their demand like user search price's value, category, name, brand whatever users want.

     

     

     Search with multiple fields

     

     

       let data = await Product.find(
          {
             "$or": [
                   { "name": {$regex: req.params.key}},
                   { "brand": {$regex: req.params.key}}
                   ]
        }
       )
       resp.send(data)
       
    })
    
    

     

     

    const express = require('express');
    require('./config')
    const Product = require('./product')
    const app = express();
    
    app.use(express.json());
    
    app.get('/search/:key', async (req, resp) => {
       console.log(req.params.key);
       let data = await Product.find(
          {
             "$or": [
                   { "name": {$regex: req.params.key}},
                   { "brand": {$regex: req.params.key}}
                   ]
        }
       )
       resp.send(data)
       //resp.send('Done')
    })
    
    app.listen(8000)
    

     

     

     

    Search API with multiple filed in nodejs

     

     

     



    Disclaimer



    All tutorials are for informational and educational purposes only and have been made using our own routers, servers, websites and other vulnerable free resources. we do not contain any illegal activity. We believe that ethical hacking, information security and cyber security should be familiar subjects to anyone using digital information and computers. Hacking Truth is against misuse of the information and we strongly suggest against it. Please regard the word hacking as ethical hacking or penetration testing every time this word is used. We do not promote, encourage, support or excite any illegal activity or hacking.

     

     

  • WHAT WE DO

    We've been developing corporate tailored services for clients for 30 years.

    CONTACT US

    For enquiries you can contact us in several different ways. Contact details are below.

    Hacking Truth.in

    • Street :Road Street 00
    • Person :Person
    • Phone :+045 123 755 755
    • Country :POLAND
    • Email :contact@heaven.com

    Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

    Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation.