Open In App

How to get YouTube video thumbnail using Node.js ?

Improve
Improve
Like Article
Like
Save
Share
Report

The following approach covers how to get the YouTube video thumbnails in nodeJs. We will use the youtube-thumbnail node-package to achieve so. This package will help us for getting the YouTube video thumbnail with the help of the video URL or watch code.

Use the following steps to install the module and get the YouTube video thumbnail in node.js:

Step 1: Creating a directory for our project and making that our working directory.

$ mkdir youtube-extract-gfg
$ cd youtube-extract-gfg

Step 2: Use the npm init command to create a package.json file for our project.

$ npm init
or
$ npm init -y /* For auto add the required field */

Note: Keep pressing enter and enter “yes/no” accordingly at the terminus line.

Step 3: Installing the Express.js and youtube-thumbnail module. Now in your youtube-extract-gfg(name of your folder) folder type the following command line:

$ npm install express youtube-thumbnail

Step 4: Creating index.js file, our Project structure will look like this.

Step 5: Creating a basic server. Write down the following code in the index.js file.

index.js




const express = require('express');
const app = express();
    
app.get('/' , (req , res)=>{
    res.send("GeeksforGeeks");
});
    
// Server setup
app.listen(4000 , ()=>{
    console.log("server is running on port 4000");
});


Output: We will get the following output on the browser screen.

GeeksforGeeks

Step 6: Now let’s implement the functionality by which we get the YouTube video thumbnail.

index.js




const express = require('express');
const youtubeThumbnail = require('youtube-thumbnail');
const app = express();
    
// Basic Server
app.get('/' , (req , res)=>{
    res.send("GeeksforGeeks");
});
    
// YouTube thumbnail request handler
app.get('/:watchCode' , (req , res) => {
    var watchCode = req.params.watchCode;
    var url = `https://www.youtube.com/watch?v=${watchCode}`;
    var data = youtubeThumbnail(url);
    var thumbnail = data.high.url;
    res.send(`<img src="${thumbnail}" alt="Thumbnail" />`);
});
  
// Server setup
app.listen(4000 , ()=>{
    console.log("server is running on port 4000");
});


Step 7: Run the server using the following command.

node index.js

Output:



Last Updated : 16 Mar, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads