<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: yashvant vala</title>
    <description>The latest articles on DEV Community by yashvant vala (@yashvant).</description>
    <link>https://dev.to/yashvant</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F766647%2F4ef7dec3-d6a4-4c4f-b06a-bb2d0060a96b.jpg</url>
      <title>DEV Community: yashvant vala</title>
      <link>https://dev.to/yashvant</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/yashvant"/>
    <language>en</language>
    <item>
      <title>Polyfills for Array methods: forEach(), map(), filter(), reduce(),find()</title>
      <dc:creator>yashvant vala</dc:creator>
      <pubDate>Wed, 22 Jun 2022 15:48:09 +0000</pubDate>
      <link>https://dev.to/yashvant/polyfills-for-array-methods-foreach-map-filter-reducefind-3heg</link>
      <guid>https://dev.to/yashvant/polyfills-for-array-methods-foreach-map-filter-reducefind-3heg</guid>
      <description>&lt;p&gt;It's been a long time since I haven't written any articles but here we go.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Note: if you don't know what polyfills are then please read this &lt;a href="https://javascript.info/polyfills"&gt;article&lt;/a&gt;.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  forEach()
&lt;/h2&gt;

&lt;p&gt;Here is the sample code for how forEach will work.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const person = [
  {
    id:1,
    name:'user1',
    isActive: true,
  },
  {
    id:2,
    name:'user2',
    isActive: true,
  }, 
  {
    id:3,
    name:'user3',
    isActive: true,
  }, 
  {
    id:4,
    name:'user4',
    isActive: true,
  }  
]

person.forEach(data=&amp;gt;{
  data.isActive = false;
})

console.log(person)

Output:

[
  { id: 1, name: 'user1', isActive: false },
  { id: 2, name: 'user2', isActive: false },
  { id: 3, name: 'user3', isActive: false },
  { id: 4, name: 'user4', isActive: false }
]

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here I am manipulating the isActive to false. so how can we create our own method like this, to know that see the below example&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const person = [
  {
    id:1,
    name:'user1',
    isActive: true,
  },
  {
    id:2,
    name:'user2',
    isActive: true,
  }, 
  {
    id:3,
    name:'user3',
    isActive: true,
  }, 
  {
    id:4,
    name:'user4',
    isActive: true,
  }  
]
Array.prototype.myForEach = function(callback){
  for(let i=0;i&amp;lt;this.length;i++){
    callback(this[i],i, this);
  }
}

person.myForEach(data=&amp;gt;{
  data.isActive = false;
})

console.log(person)

Output:

[
  { id: 1, name: 'user1', isActive: false },
  { id: 2, name: 'user2', isActive: false },
  { id: 3, name: 'user3', isActive: false },
  { id: 4, name: 'user4', isActive: false }
]

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above example, I have named the method as myForEach and added it to the prototype of the array so it can be available for any array data structure. once we add the method we can use the array using this keyword because we are calling the method using the (.) operator with the array, which means the context of this will be the object where we have called the method.&lt;/p&gt;

&lt;p&gt;And above example will give the same output as forEach().&lt;/p&gt;

&lt;h2&gt;
  
  
  Map()
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const person = [
  {
    id:1,
    name:'user1',
    isActive: true,
  },
  {
    id:2,
    name:'user2',
    isActive: true,
  }, 
  {
    id:3,
    name:'user3',
    isActive: true,
  }, 
  {
    id:4,
    name:'user4',
    isActive: true,
  }  
]

const newPerson = person.map(data=&amp;gt;{
  return {...data, isActive:false};
})

console.log(newPerson)

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above code, we are making isActive as false and it will return a new array, unlike forEach. So the output would be something like this.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Output:

[
  { id: 1, name: 'user1', isActive: false },
  { id: 2, name: 'user2', isActive: false },
  { id: 3, name: 'user3', isActive: false },
  { id: 4, name: 'user4', isActive: false }
]

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;below is the polyfill for the map method,&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Array.prototype.myMap = function(callback){
  const newArray = [];
  for(let i=0;i&amp;lt;this.length;i++){
    newArray.push(callback(this[i],i, this));
  }
  return newArray;
}

const newPerson = person.myMap(data=&amp;gt;{
  return {...data, isActive:false};
})

console.log(newPerson)

Output:

[
  { id: 1, name: 'user1', isActive: false },
  { id: 2, name: 'user2', isActive: false },
  { id: 3, name: 'user3', isActive: false },
  { id: 4, name: 'user4', isActive: false }
]

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It is very similar to forEach, the difference is just we are returning a new array with the result of the callback function. so the output will be the same.&lt;/p&gt;

&lt;h2&gt;
  
  
  Filter()
&lt;/h2&gt;

&lt;p&gt;See below example where we are filtering the users based on the isActive parameter.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const person = [
  {
    id:1,
    name:'user1',
    isActive: true,
  },
  {
    id:2,
    name:'user2',
    isActive: false,
  }, 
  {
    id:3,
    name:'user3',
    isActive: true,
  }, 
  {
    id:4,
    name:'user4',
    isActive: false,
  }  
]

const newPerson = person.filter(data=&amp;gt;{
  return data.isActive;
})

console.log(newPerson)

Output:

[
  { id: 1, name: 'user1', isActive: true },
  { id: 3, name: 'user3', isActive: true }
]

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;it is similar to a map but it will only return those items which match the condition in the return statement. so let's write polyfill for that&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Array.prototype.myFilter = function(callback){
  const newArray = [];
  for(let i=0;i&amp;lt;this.length;i++){
    if(callback.call(this, this[i],i, this)){
      newArray.push(this[i]);
    }
  }
  return newArray;
}
const person = [
  {
    id:1,
    name:'user1',
    isActive: true,
  },
  {
    id:2,
    name:'user2',
    isActive: false,
  }, 
  {
    id:3,
    name:'user3',
    isActive: true,
  }, 
  {
    id:4,
    name:'user4',
    isActive: false,
  }  
]

const newPerson = person.myFilter(data=&amp;gt;{
  return data.isActive;
})

console.log(newPerson)

Output:

[
  { id: 1, name: 'user1', isActive: true },
  { id: 3, name: 'user3', isActive: true }
]

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here we are calling the callback using call method to provide the context of an array. when if the condition becomes true then we are pushing the array and we are only returning those items which satisfy the condition.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const person = [
  {
    id:1,
    name:'user1',
    isActive: true,
    balance: 20,
  },
  {
    id:2,
    name:'user2',
    isActive: false,
    balance: 30,
  }, 
  {
    id:3,
    name:'user3',
    isActive: true,
    balance: 40,
  }, 
  {
    id:4,
    name:'user4',
    isActive: false,
    balance: 50,
  }  
]

const totalBalance = person.reduce((accumulator,data)=&amp;gt;{
  return accumulator+=data.balance;
}, 0)

console.log(totalBalance)

Output:

140

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here I've added one more field called balance and I want the total sum of the balance so we can use the reduce method to make the sum out of it. note that the callback function first argument will be the different and we have provided the initial value as 0.&lt;/p&gt;

&lt;p&gt;let's see the polyfill for reduce method in the below example.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Array.prototype.myReduce = function(callback, initialValue){
  let accumulator = initialValue===undefined ? undefined: initialValue;
  for(let i=0;i&amp;lt;this.length;i++){
    if(accumulator!==undefined){
      accumulator = callback.call(undefined, accumulator, this[i], i, this)
    }else{
      accumulator = this[i];
    }
  }
  return accumulator;
}
const person = [
  {
    id:1,
    name:'user1',
    isActive: true,
    balance: 20,
  },
  {
    id:2,
    name:'user2',
    isActive: false,
    balance: 30,
  }, 
  {
    id:3,
    name:'user3',
    isActive: true,
    balance: 40,
  }, 
  {
    id:4,
    name:'user4',
    isActive: false,
    balance: 50,
  }  
]

const totalBalance = person.myReduce((accumulator,data)=&amp;gt;{
  return accumulator+=data.balance;
}, 0)

console.log(totalBalance)

Output

140

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;here we are passing one more parameter which is the initial value, we are calling the callback using call method and assigning the result to the accumulator so we will get the sum out of it or whatever logic we have written inside the callback function.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Note: don't forget to provide the initial value otherwise as we can see in the polyfill it will assign this[i] means the whole object and we have to extract the value out of it.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  Find()
&lt;/h2&gt;

&lt;p&gt;find() is very similar to the filter method but here we are only sending one result.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const foundPerson = person.find(data=&amp;gt;{
  return data.name === 'user1';
})

console.log(foundPerson)

Output:

{ id: 1, name: 'user1', isActive: true, balance: 20 }

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As we can see the output that it will only return one record.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Array.prototype.myFind = function(callback, initialValue){
  for(let i=0;i&amp;lt;this.length;i++){
    if(callback.call(accumulator, this[i], i, this)){
      return this[i]
    }
  }
  return accumulator;
}
const person = [
  {
    id:1,
    name:'user1',
    isActive: true,
    balance: 20,
  },
  {
    id:2,
    name:'user2',
    isActive: false,
    balance: 30,
  }, 
  {
    id:3,
    name:'user3',
    isActive: true,
    balance: 40,
  }, 
  {
    id:4,
    name:'user4',
    isActive: false,
    balance: 50,
  }  
]

const foundPerson = person.find(data=&amp;gt;{
  return data.name === 'user1';
})

console.log(foundPerson)

Output

{ id: 1, name: 'user1', isActive: true, balance: 20 }

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the polyfill, we are directly returning the record which matches the condition,&lt;/p&gt;

&lt;p&gt;Similarly, there is one more method findIndex which is very same as find, this method will return the index of the array record which match the condition, to achieve that in find polyfill you can write in return statement as return i instead of return this[i] and in else block you can return -1.&lt;/p&gt;

&lt;p&gt;So this was it for the polyfill, Hope you get some knowledge from here and if any doubt please write me comment, i would be glad to solve your doubt.&lt;/p&gt;

&lt;p&gt;More polyfills are coming, stay tuned and see you in the next article!&lt;/p&gt;

&lt;p&gt;signing off!&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>polyfill</category>
      <category>react</category>
    </item>
    <item>
      <title>Upload/Download/Delete files on AWS S3 bucket using node.js</title>
      <dc:creator>yashvant vala</dc:creator>
      <pubDate>Tue, 14 Dec 2021 04:44:31 +0000</pubDate>
      <link>https://dev.to/yashvant/uploaddownloaddelete-files-on-aws-s3-bucket-using-nodejs-50ln</link>
      <guid>https://dev.to/yashvant/uploaddownloaddelete-files-on-aws-s3-bucket-using-nodejs-50ln</guid>
      <description>&lt;p&gt;What is aws s3?&lt;/p&gt;

&lt;p&gt;Aws s3 stands for simple storage service provided by amazon web service.&lt;/p&gt;

&lt;p&gt;Here are some of the use cases of aws s3&lt;/p&gt;

&lt;p&gt;Static Website Hosting&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;you can host any static web site which is built in (react,nextjs,angular, vue, gatsby,remix).&lt;br&gt;
Archive Data&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;you can archive much of the data with low cost.&lt;br&gt;
Backups (most used)&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;you can store your backups like db backup every day using cron job.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Also there are some additional advantage of it which you can explore in &lt;a href="https://s3.console.aws.amazon.com/s3/home" rel="noopener noreferrer"&gt;aws console&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Let's understand how s3 works.&lt;/p&gt;

&lt;p&gt;In order to use s3, you need to create a bucket where you want to store anything. you can compare it to folder where all files are stored.&lt;/p&gt;

&lt;p&gt;Each bucket has unique name and you can create folder/files in the bucket. It stores data as key value pair. We will see in further that how it stores data in key value pair. S3 provides storage limit 0 to 5 TB.&lt;/p&gt;

&lt;p&gt;Generally Root user of aws creates Identity and Access Management (IAM) user to provide access of aws with some rules.&lt;/p&gt;

&lt;p&gt;IAM user can create bucket, and also can perform some operations on it.&lt;/p&gt;

&lt;p&gt;In order to create IAM user, you need to create account on &lt;a href="https://aws.amazon.com/" rel="noopener noreferrer"&gt;aws&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Once you have created account, you can find IAM user creation option. After creating IAM user, create the s3 bucket using s3 option. See the below image.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F10qv4ynu6z9q2jvqs4od.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F10qv4ynu6z9q2jvqs4od.jpg" alt="S3 Scereen" width="800" height="444"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Once you click on s3 you will find following screen.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fx8qqbirvq2i359qrz6ub.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fx8qqbirvq2i359qrz6ub.jpg" alt="Image description" width="800" height="156"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Click on the create bucket and fill all the data, You will also need to select rules like permissions and all.&lt;/p&gt;

&lt;p&gt;After creating a bucket aws will provide you Access key id and Secret access key.&lt;/p&gt;

&lt;p&gt;Save those key in your machine because we will need those keys in order to perform any actions on it.&lt;/p&gt;

&lt;p&gt;Now create a new nodejs project using following command. (I assume that you have downloaded node in your machine).&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm init -y
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;blockquote&gt;
&lt;p&gt;-y is a flag which is used when you want to give yes to all questions which is asked when you create node project.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Install few dependencies to create an app.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm i express dotenv express-fileupload
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Above dependecies are used to create express server and upload files. dotenv file is for storing the private keys provided by aws.&lt;/p&gt;

&lt;p&gt;Now create index.js file with following code.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const express = require("express");
const app = express();
const fileUpload = require("express-fileupload");

//express middlewares
app.use(fileUpload({
    useTempFiles:true,
    tempFileDir:"/tmp"
}));



const PORT = process.env.PORT || 4000;
app.listen(PORT,()=&amp;gt;console.log(`server is running on port ${PORT}`));

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We will need express file upload middleware to upload files, we also can create own functionality to create temporary folder and store file in folder, once it is uploaded we can delete that folder.&lt;/p&gt;

&lt;p&gt;Let's create two folder, Rotues and utils.&lt;/p&gt;

&lt;p&gt;In routes folder we will create routes of api and we will send response based on actions, We surely can create controller folder but as of our job can be done using route.&lt;/p&gt;

&lt;p&gt;In utils (utility) folder we will create one file which is called s3.js to perform some actions based on s3.&lt;/p&gt;

&lt;p&gt;GO to routes folder and create file with .js extension, Here I have created uploadFile.js&lt;/p&gt;

&lt;p&gt;Write following thing in that file.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
const router = require('express').Router();
const s3 = require("../utils/s3");

router.post("/upload",(req,res)=&amp;gt;{
    const file = req.files.file;
    s3.uploadToS3(file,(error,data)=&amp;gt;{
        if(error){
            return res.send({error:"Something went wrong."});
        }
        return res.send({message:"File uploaded successfully"});
    });
});

module.exports = router;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here we are having post method, We will get one file from front-end or you can use post man here.&lt;/p&gt;

&lt;p&gt;s3.uploadToS3 is the function which we will create in s3.js file to upload file, we will also return call back with data and error.&lt;/p&gt;

&lt;p&gt;Important&lt;/p&gt;

&lt;p&gt;We will need to install aws sdk dependency to perform action in aws s3&lt;/p&gt;

&lt;p&gt;So write following command&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm i aws-sdk

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;After Installing it , go to s3.js file and import following things.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const path = require('path');
const fs = require('fs');
const fileUpload = require('express-fileupload');
const aws = require('aws-sdk');

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now we will need to configure the aws to create connection between our app and aws.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//configure the aws environment
aws.config.update({
    accessKeyId:process.env.AWS_ACCESS_KEY_ID,
    secretAccessKey:process.env.AWS_SECRET_ACCESS_KEY,
});

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Above code is just used to create environment of s3.&lt;/p&gt;

&lt;p&gt;now create instance of s3 so we can use all methods of s3.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//initialize s3
const s3 = new aws.S3();

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now we can create our function to upload files which we are calling in our uploadFiles.js&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;exports.uploadToS3 = (file,next) =&amp;gt;{
    const fileStream = fs.createReadStream(file.tempFilePath);
    console.log(file.tempFilePath)
    const params = {
        Bucket:process.env.AWS_BUCKET_NAME,
        Body:fileStream,
        Key:file.name
    };
    s3.upload(params,(error,data)=&amp;gt;{
        console.log(error,data);
        next(error,data);
    });
};

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So we will need some parameters to send to s3, so s3 can know that where to upload file and in which bucket to.&lt;/p&gt;

&lt;p&gt;We will send bucket name, Body means the data which we want to upload and key which you can give any name. I will just give the file name as key name.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;s3.upload method accept parameters and based on it it return call back function of data and error.&lt;/p&gt;

&lt;p&gt;We will send data and error in our callback function, which we are getting in uploadFiles.js&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Now you can go to index.js and import following things.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const uploadFiles = require("./routes/uploadFiles");

//you use this as a moddleware of routes

//our base api route will be /api/v1/*
app.use("/api/v1",uploadFiles);

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So final index.js will be look like this.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const express = require("express");
const app = express();
const fileUpload = require("express-fileupload");

//express middlewares
app.use(express.json());
app.use(express.urlencoded({extended:true}));
app.use(fileUpload({
    useTempFiles:true,
    tempFileDir:"/tmp"
}));

//all routes
const uploadFiles = require("./routes/uploadFiles");

//route middlewares
app.use("/api/v1",uploadFiles);

//config http server
const PORT = process.env.PORT || 4000;
app.listen(PORT,()=&amp;gt;console.log(`server is running on port ${PORT}`));

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now we can use our api in postman. &lt;em&gt;localhost:4000/api/v1/upload&lt;/em&gt; is the url to can api.&lt;/p&gt;

&lt;p&gt;See the image below to select configuration to send file.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fju6qcc9eah6iz38340ih.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fju6qcc9eah6iz38340ih.jpg" alt="Postman Screen" width="800" height="497"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;I have selected image file so it will be uploaded on s3. You Also can verify on s3 whether it is uploaded or not.&lt;/p&gt;

&lt;p&gt;Once it is uploaded we will get following metadata by s3.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;ETag: 'some random string',
  Location: your url of file,
  key: 'horizontal_tagline_on_white_by_logaster.jpeg',
  Key: 'horizontal_tagline_on_white_by_logaster.jpeg',
  Bucket: your bucket name

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We can store key and location in our db so in future we can select or delete anything based on key.&lt;/p&gt;

&lt;p&gt;Now we can create download and delete file functionality which is much easier.&lt;/p&gt;

&lt;p&gt;Since we need bucket name in all the parameter which we will pass in all methods, I will make and object so we don't need to write it again.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const constantParams = {
    Bucket:process.env.AWS_BUCKET_NAME
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So now Our s3.js file will look like this.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const path = require('path');
const fs = require('fs');
const fileUpload = require('express-fileupload');
const aws = require('aws-sdk');

//configure the aws environment
aws.config.update({
    accessKeyId:process.env.AWS_ACCESS_KEY_ID,
    secretAccessKey:process.env.AWS_SECRET_ACCESS_KEY,
});

//initialize s3
const s3 = new aws.S3();

//constant params
const constantParams = {
    Bucket:process.env.AWS_BUCKET_NAME
}

//upload file to s3 bucker
exports.uploadToS3 = (file,next) =&amp;gt;{
    const fileStream = fs.createReadStream(file.tempFilePath);

    const params = {
        ...constantParams,
        Body:fileStream,
        Key:file.name
    };
    s3.upload(params,(error,data)=&amp;gt;{
        console.log(error,data);
        next(error,data);
    });
};

//download file from s3 bucket
exports.getFileFromS3 = key =&amp;gt;{
    const downloadParams = {
        Key:key,
       ...constantParams
    };
    return s3.getObject(downloadParams).createReadStream();
};

//delete file from s3 bucker
exports.deleteFileFromS3 = (key,next) =&amp;gt;{
    const deleteParams = {
        Key:key,
        ...constantParams
    };
    s3.deleteObject(deleteParams,(error,data)=&amp;gt;{

        next(error,data);
    });
};

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;blockquote&gt;
&lt;p&gt;s3.getObject method used when we want to get any file from s3&lt;/p&gt;

&lt;p&gt;s3.deleteObject method will delete the file.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;As you can see in above code our function for download and delete is expecting the key, which we get by s3 so we can pass that key&lt;/p&gt;

&lt;p&gt;Now our uploadFiles.js file will look like this.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const router = require('express').Router();
const s3 = require("../utils/s3");

router.post("/upload",(req,res)=&amp;gt;{
    const file = req.files.file;
    s3.uploadToS3(file,(error,data)=&amp;gt;{
        console.log("commit")
        if(error){
            return res.send({error:"Something went wrong."});
        }
        return res.send({message:"File uploaded successfully"});
    });
});

router.get("/getFile",async (req,res)=&amp;gt;{
    try {
        let fileToSend = await s3.getFileFromS3('horizontal_tagline_on_white_by_logaster.jpeg');
        fileToSend.pipe(res);
    } catch (error) {
        res.send({error:"Server Error"});
    }
});

router.delete("/deleteFile",(req,res)=&amp;gt;{
    s3.deleteFileFromS3('horizontal_tagline_on_white_by_logaster.jpeg',(error,data)=&amp;gt;{
        if(error){
            return res.send({error:"Can not delete file, Please try again later"});
        }
        return res.send({message:"File has been deleted successfully"});
    });
});

module.exports = router;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now you can call both download and delete api, the end point of both api will be,&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;download file : localhost:4000/api/v1/getFile/:key&lt;/p&gt;

&lt;p&gt;delete file : localhost:4000/api/v1/getFile/:key&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;I am passing the key directly because we didn't saved it in our db. but in real scenario we will be saving key in db and fetching keys to perform actions.&lt;/p&gt;

&lt;p&gt;So this is how you can perform some actions on s3. Trust me it is very easy than it seems and also depends how you want to craft you app.&lt;/p&gt;

&lt;p&gt;Hope you get something from this article, If you still confused at any point then please comment below.&lt;/p&gt;

&lt;p&gt;Thanks :)&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Schedule the DB backup cron job with nodejs</title>
      <dc:creator>yashvant vala</dc:creator>
      <pubDate>Mon, 13 Dec 2021 07:08:32 +0000</pubDate>
      <link>https://dev.to/yashvant/schedule-the-db-backup-cron-job-with-nodejs-3elg</link>
      <guid>https://dev.to/yashvant/schedule-the-db-backup-cron-job-with-nodejs-3elg</guid>
      <description>&lt;p&gt;Job scheduling has always been an important part of any application where we want to make certain tasks automatically like sending emails to the subscribed user or anything like that.&lt;/p&gt;

&lt;p&gt;In this article, we will cover that how we can make a cron job that takes DB backup automatically at a given time interval.&lt;/p&gt;

&lt;p&gt;First, we will need to create a node project, Create node app with the following command.&lt;br&gt;
&lt;/p&gt;

&lt;p&gt;&lt;code&gt;npm init -y&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;p&gt;The above command will make package.json file and -y will give all question-answer which asked during making a project.&lt;/p&gt;

&lt;p&gt;We will be using express.js and to run the cron job we will be using a package called node-cron&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm i express node-cron
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The above command will install express and node-cron package.&lt;/p&gt;

&lt;p&gt;Let's create a file called index.js and import the following things.&lt;/p&gt;

&lt;p&gt;index.js&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const { spawn } = require('child_process');
const path = require('path');
const cron = require('node-cron');
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;blockquote&gt;
&lt;p&gt;Spawn process will help us to run command in a terminal, It also does many things but we only need it to run our command.&lt;/p&gt;

&lt;p&gt;Path will be used to join the given path which will be provided along with the directory name.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The following command will dump a mongo DB backup in the format we will provide.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;mongodump --db=&amp;lt;your db name&amp;gt; --archive=./&amp;lt;path&amp;gt;.gzip --gzip

//example

mongodump --db=users --archive=./userDBBackup.gzip --gzip
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The above command will have a couple of arguments, first will be the command name which is mongodump, the Second one is DB name, the Third one is the path of the archive where we want to store the DB backup and the last one will be the compression which we want to use.&lt;/p&gt;

&lt;p&gt;Now we will create a function that will be responsible to make DB backup.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const DB_NAME = 'users';

const BACKUP_PATH= path.join(__dirname, 'public', `${DB_NAME}.gzip`);

const  backUpDB = () =&amp;gt; {
    const child = spawn('mongodump',[
        `--db=${DB_NAME}`,
        `--archive=${BACKUP_PATH}`,
        '--gzip'
    ]);
    child.stdout.on('data',(data)=&amp;gt;{
        console.log('stdoup',data)
    })
    child.stderr.on('data',(data)=&amp;gt;{
        console.log('stdoup',Buffer.from(data).toString())
    })
    child.on('error',(err)=&amp;gt;{
        console.log(err);
    })
    child.on('exit',(code,signal)=&amp;gt;{
        if(code){
            console.log('process exit with code', code)
        }else if(signal){
            console.log('process killed with signal',signal)
        }else{
            console.log("back up success");
        }
    })
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let's understand the above code.&lt;/p&gt;

&lt;p&gt;So path.join method will join the two-path, __dirname will return the current directory of our location, and also we can provide directory name and file name in the argument.&lt;/p&gt;

&lt;p&gt;Spawn will execute the command in a terminal, It takes the first argument as a command name and another argument will be an array of all parameters of a command. Here we just wrote the command of DB backup.&lt;/p&gt;

&lt;p&gt;Now we will need to handle the output as well as the error which comes from the terminal or from the file itself.&lt;/p&gt;

&lt;p&gt;So stdout will return the output if our command has been executed successfully, It will return a callback function and in the argument, it provides the data.&lt;/p&gt;

&lt;p&gt;stderr will return the error if the command is not found or something wrong related to the command or terminal.&lt;/p&gt;

&lt;p&gt;Now the third thing is the simple error that can occur in our file. We will also check the code and signal if the process is failed due to some issue.&lt;/p&gt;

&lt;p&gt;Let's create a job that can run at a certain time interval and we will call our function there.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;If you want to learn more about job scheduling then &lt;a href="https://blog.yashvant.in/cron-jobaka-job-scheduling-with-nodejs"&gt;click here&lt;/a&gt;, This link is from one of my articles on a cron job.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;So following code will run the job at a given time.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Scheduling the database backup every night
cron.schedule('00 00 00 * * *', () =&amp;gt; backUpDB ());
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here schedule method expects arguments which is the time when we want to run the DB backup code.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;To learn more about the combination of different times &lt;a href="https://crontab.guru/examples.html"&gt;click here&lt;/a&gt;.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;So the final code will look like this.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const { spawn } = require('child_process');
const path = require('path');
const cron = require('node-cron');

const DB_NAME = 'users';

const BACKUP_PATH= path.join(__dirname, 'public', `${DB_NAME}.gzip`);

const  backUpDB = () =&amp;gt; {
    const child = spawn('mongodump',[
        `--db=${DB_NAME}`,
        `--archive=${BACKUP_PATH}`,
        '--gzip'
    ]);
    child.stdout.on('data',(data)=&amp;gt;{
        console.log('stdoup',data)
    })
    child.stderr.on('data',(data)=&amp;gt;{
        console.log('stdoup',Buffer.from(data).toString())
    })
    child.on('error',(err)=&amp;gt;{
        console.log(err);
    })
    child.on('exit',(code,signal)=&amp;gt;{
        if(code){
            console.log('process exit with code', code)
        }else if(signal){
            console.log('process killed with signal',signal)
        }else{
            console.log("back up success");
        }
    })
}

// Scheduling the database backup every night
cron.schedule('00 00 00 * * *', () =&amp;gt; backUpDB ());
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So this was a simple article on how you can backup the database.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Note - You can backup any database by their corresponding commands, You just need to pass some arguments in the spawn.&lt;/p&gt;

&lt;p&gt;Tip - You also can upload backup on any cloud like AWS S3 or google drive, cloudinary, or anything like that. You can check my another article to know more about uploading files in the cloud.&lt;a href="https://blog.yashvant.in/uploaddownloaddelete-any-file-on-aws-s3-bucket-using-nodejs"&gt;https://blog.yashvant.in/uploaddownloaddelete-any-file-on-aws-s3-bucket-using-nodejs&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Thanks :)&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Host React/Angular/Vue Site on Netlify</title>
      <dc:creator>yashvant vala</dc:creator>
      <pubDate>Sun, 12 Dec 2021 13:03:25 +0000</pubDate>
      <link>https://dev.to/yashvant/host-reactangularvue-site-on-netlify-20gb</link>
      <guid>https://dev.to/yashvant/host-reactangularvue-site-on-netlify-20gb</guid>
      <description>&lt;p&gt;Hosting your own site is really easy, In this article we gonna see how can we host our front end in netlify.&lt;/p&gt;

&lt;p&gt;Also hosting concept will be the same whether it is netlify or vercel or heroku. If you learn any of them then you will be able to host your static site anywhere.&lt;/p&gt;

&lt;p&gt;So let's start&lt;/p&gt;

&lt;p&gt;Step 1:- Create sample website(maybe in react/angular/nextjs) and push it in GitHub&lt;/p&gt;

&lt;p&gt;Step 2:- Sign up to Netlify&lt;/p&gt;

&lt;p&gt;Once you have singed up you will see the following screen.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--G5XIF01x--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3ldbl66fvo6cfaf9wkda.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--G5XIF01x--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3ldbl66fvo6cfaf9wkda.jpg" alt="Main screen" width="880" height="495"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now click on the &lt;strong&gt;new site from git&lt;/strong&gt; button.&lt;/p&gt;

&lt;p&gt;After click on it, you will see the following screen.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--6no1U-bT--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/owkpcl5vh7377n3jt3x3.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--6no1U-bT--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/owkpcl5vh7377n3jt3x3.jpg" alt="Netlify home screen" width="880" height="495"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Step 3 :- Select the platform where you have pushed your code (in our case it will be github)&lt;/p&gt;

&lt;p&gt;Once you select the platform you need to authorize the platform to access the repo of your site.&lt;/p&gt;

&lt;p&gt;You will see the following screen once you click on github or any button.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--61WVDDvm--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wy62qd9qdpm9pu9mbrtn.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--61WVDDvm--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wy62qd9qdpm9pu9mbrtn.jpg" alt="Netlify site selection screen" width="880" height="495"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;You can search/select any private/public repo of your GitHub etc. and can select it.&lt;/p&gt;

&lt;p&gt;Once you select repo/project to deploy, you will see below screen.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--JJZrsbKi--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ujlrqr7yi27u1nis4dek.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--JJZrsbKi--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ujlrqr7yi27u1nis4dek.jpg" alt="Netlify deployment screen" width="880" height="495"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now you can select relevent branch of your project and you need to set command to build your project and you have to provide the path of your site build. If you have react project the it will be npm run build and for angular it will be ng build, you also can find build command in package.json or just google it.&lt;/p&gt;

&lt;p&gt;You will see below screen after you clicked on &lt;strong&gt;deploy site&lt;/strong&gt; button.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--gv6jXrrD--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8jvhh8mjiuw0yujxit9p.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--gv6jXrrD--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8jvhh8mjiuw0yujxit9p.jpg" alt="project setting" width="880" height="495"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Here my site name will be &lt;strong&gt;thirsty-hoover-727570.netlify.app&lt;/strong&gt;,  you can also change the domain name or you can provide custom domain.&lt;/p&gt;

&lt;p&gt;You can change domain name in domain setting which will be similar to below image.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--sSWi8jDk--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wi7olax5fdwqde6u94vg.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--sSWi8jDk--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wi7olax5fdwqde6u94vg.jpg" alt="domain change" width="880" height="495"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;So that's it, how easy it was.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Note - If you want to make update in your website you need to push latest code to your repo and you need to redeploy it, you will find the option for redeployment in your project on netlify.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Thanks for reading, let me know in comment section if there is anything which is difficult to understand.&lt;/p&gt;

</description>
    </item>
  </channel>
</rss>
