2014-12-26 3 views
0
var yModule = require('youtube-node'), 
    nodeYoutube = new yModule(); 

nodeYoutube.setKey("key"); 

module.exports.getVideoLength = function (vData){ 
    youTube.getById(vData, function (result) { 
     return convertTime(result['items'][0]['contentDetails']['duration']); 
    }) 
}; 

var convertTime = function (time){ 
    var reptms = /(?:(\d+)DT)?(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?$/; 
    var days = "00", hours = "00", minutes = "00", seconds = "00", formattedTime; 


    //if (reptms.test(time)) { 
     var matches = reptms.exec(time); 
     console.log(matches); 
     if (matches[1]) days = String(matches[1]); 
     if (matches[2]) hours = String(matches[2]); 
     if (matches[3]) minutes = String(matches[3]); 
     if (matches[4]) seconds = String(matches[4]); 
     formattedTime = "[" + days + ":" + hours + ":" + minutes + ":" + seconds + "]"; 
     return formattedTime; 
    //} 
}; 

콜백에 대해 몇 가지 내용을 읽은 후에도 이해하기가 어렵습니다. nodeJs callbacks simple example 조금 도움이되었지만 작동 방식에 대해 아직 명확하지 않습니다. 지난 시간에 콜백을 사용하여 이것을 작성하는 방법을 알아 내려고 노력했습니다. 콜백을 사용해야합니까?

이 모듈

이 호출되고 :

ytRetrieve.getVideoLength(youtube_parser(text)) 

youtube_parser의 기능 : 당신은 콜백을 사용할 필요가

function youtube_parser(url){ 
    var regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/; 
    var match = url.match(regExp); 
    //console.log(match); 
    if (match&&match[7]){ 
     return match[7].split(" ")[0]; 
    } 
} 
+0

'무엇을 bot'입니까? 이것을 만들었나요 아니면 다른 모듈입니까? –

+0

@ExplosionPills 그것은 'irc'모듈입니다 – ECMAScript

+0

이것은 들뜬 일입니다. 콜백이 필요한지 묻는 사용자 이름 "ECMAScript" 짧은 대답 : 예, 항상, 특히 노드에서. 여기에 훌륭한 콜백 리소스가 있습니다. (http://javascriptissexy.com/understand-javascript-callback-functions-and-use-them/) 당신의 머리를 감싸는 데 도움이됩니다. 건배! –

답변

0

다음은 내가 생각해 낸 해결책입니다. 이 코드를 향상시키기 위해 할 수있는 일이 있습니까?

도움 주셔서 감사합니다.

Main.js

var ytempRetrieve = require('./youtube'), ytRetrieve = new ytempRetrieve(); 

var ytRegex = /(?:https?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))((\w|-){11})(?:\S+)?/; 


bot.addListener('message', function (from, to, text, message) { 
    if (text.match(ytRegex)) { 
     console.log(text); 
     youtube_parser(text, to, ytRetrieve.getVideoLength) 
    } 
}); 

function youtube_parser(url, to, callback) { 
    var regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/; 
    var match = url.match(regExp); 
    //console.log(match); 
    if (match && match[7]) { 
     callback(match[7].split(" ")[0], function (res) { 
      setTimeout(function() { 
       bot.say(to, match[7].split(" ")[0] + " is " + res + " long.") 
      }, 1500) 
     }); 
    } 
} 

youtube.js

var yModule = require('youtube-node'), 
    nodeYoutube = new yModule(), 
    apiKey = require('./config'); 


    var youtube = function() { 
    var self = this; 

    self.time = null; 

    self.setAPIKey = function (key) { 
     nodeYoutube.setKey(key); 
    }; 

    apiKey.getAPIKey(self.setAPIKey); 

    self.getVideoLength = function (vData, callback) { 
     nodeYoutube.getById(vData, function (result) { 
      callback(self.convertTime(result['items'][0]['contentDetails']['duration'])); 
     }) 
    }; 

    self.convertTime = function (time) { 
     var reptms = /(?:(\d+)DT)?(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?$/; 
     var days = 0, hours = 0, minutes = 0, seconds = 0, formattedTime; 

     //if (reptms.test(time)) { 
     var matches = reptms.exec(time); 
     console.log(matches); 
     if (matches[1]) days = Number(matches[1]); 
     if (matches[2]) hours = Number(matches[2]); 
     hours += days * 24; 
     if (hours.toString().length === 1) { 
      hours = "0" + hours 
     } 
     if (matches[3]) minutes = String(matches[3]); 
     if (minutes.toString().length === 1) { 
      minutes = "0" + minutes 
     } 
     if (matches[4]) seconds = String(matches[4]); 
     if (seconds.toString().length === 1) { 
      seconds = "0" + seconds 
     } 
     formattedTime = "[" + hours + ":" + minutes + ":" + seconds - 1 + "]"; 
     return (formattedTime); 
     //} 
    }; 

}; 

module.exports = youtube; 
0

. 귀하의 코드 youtube_parser(의 문제는 입니다. 전화 번호는입니다. 콜백은 나중에 호출 할 인수로 전달되는 함수입니다. 함수를 호출하면 문자열이 반환됩니다. getVideoLength은 문자열이 아닌 인수로 함수를 예상합니다.

대신 getVideoLength(youtube_parser)을 사용하십시오. 실제로 youtube_parser 함수 자체에서 전달되어 나중에 호출됩니다 (즉, getVideoLength이 완료 될 때). 대신 youtube_parser에 대한 인수는 (error, url) 일 필요가 있습니다.

+0

"콜백은 나중에 호출 할 인수로 전달되는 함수입니다." 나는 이것을 이해하지 못한다. 그리고 오류 매개 변수로 무엇을합니까? youtube_parser가 값을 반환 한 후에 getVideoLength를 호출하려고합니다. – ECMAScript

+0

해결 방법으로 업데이트되었습니다. 정의되지 않았습니다. 함수 오류가 아닙니다. – ECMAScript

+0

@ECMAScript 무엇에 대해 이해하지 못합니까? 인수로 문자열, 정수 또는 부울을 전달할 수 있습니다. 왜 함수가 아닌가? –

관련 문제