Friday 5 May 2017

Javascript function returned an undefined value in NodeJs (Express)

I am writing a nodejs function that download a video from youtube. The function should return whether or not the video was downloaded. The code below should print Invalid Link but instead I get undefined. I am new to NodeJs and Js. Please Help.

var youtubedl = require('youtube-dl');
var fs = require('fs');

var videoName="";
var results="";

function getVideo(videoLink) {

    var video = youtubedl(videoLink);

    video.on('error',function (err) {
    //console.log(err.message);
    results = "Invalid Link"
    });

    video.on('info', function (info) {
        console.log('Download started');
        //console.log('Title: ' + info.title);
        //console.log('Description: ' + info.description);
        //console.log('size: ' + info.size);
        videoName = info.title;
    });

    video.on('end', function () {
        //console.log("Finished Downloading Video");
        results = "Finished Downloading Video";
    });

    video.pipe(fs.createWriteStream('youtubeVideo.mp4'));
    return results;
};

console.log(getVideo("Some Invalid Link"));

module.exports.getVideo = getVideo;


via Kev

No comments:

Post a Comment