我有一个简单的nodejs脚本来下载youtube视频并转换为mp3。我有一些承诺模式的问题,需要一些帮助。基本上,只有一个resolve();
,但脚本永远不会到达那个部分。如果我在resolve();
console.log('Finished downloading! start to convert to mp3');
它开始工作,所以问题是与resolve();
坐在一边的回调函数有关。
完整代码:https://github.com/kenpeter/test_youtube_dl
代码段:
// input
var input = [
"https://www.youtube.com/watch?v=YWZ7KtRSoAo",
"https://www.youtube.com/watch?v=0kdbu8RZNaY"
];
// lib
var youtubedl = require('youtube-dl');
// fs
var fs = require('fs');
// ffmpeg
var ffmpeg = require('fluent-ffmpeg');
// Promise
var Promise = require("bluebird");
// https://www.promisejs.org/
function youtubedl_get_info() {
return new Promise(function (resolve, reject){
youtubedl.getInfo(input, function(err, info) {
if (err) {
reject(err);
}
else
{
//console.log(info);
resolve(info);
}
});
});
}
youtubedl_get_info().then(function(infos) {
// info is array
// http://bluebirdjs.com/docs/api/promise.each.html
Promise.each(infos, function(info) {
// return new promise
return new Promise(function(resolve, reject) {
// output
var video_output = info._filename.replace(/[&\/\\#,+()$~%'":*?<>{}\ ]/g, "_");
var audio_title = info.title;
audio_title = audio_title.replace(/[&\/\\#,+()$~%'":*?<>{}\ ]/g, "_");
// dl zero
var downloaded = 0;
// fs file exist sync
if (fs.existsSync(video_output)) {
downloaded = fs.statSync(video_output).size;
}
var video = youtubedl(
info.webpage_url,
['--format=18'],
{ start: downloaded, cwd: __dirname + "/video" }
);
video.on('info', function(info) {
console.log('Download started');
console.log('filename: ' + video_output);
var total = info.size + downloaded;
console.log('size: ' + total);
if (downloaded > 0) {
console.log('resuming from: ' + downloaded);
console.log('remaining bytes: ' + info.size);
}
});
video.pipe(fs.createWriteStream("./video/" + video_output, { flags: 'a' }));
video.on('complete', function complete(info) {
'use strict';
console.log('filename: ' + video_output + ' already downloaded.');
});
video.on('end', function() {
console.log('Finished downloading! start to convert to mp3');
// It seems I cannot do more async here.
// https://codedump.io/share/KVSJfXwwlRSI/1/nodejs--how-to-pipe---youtube-to-mp4-to-mp3
var proc = new ffmpeg({source: "./video/" + video_output});
proc.setFfmpegPath('/usr/bin/ffmpeg');
proc.saveToFile("./audio/" + audio_title + ".mp3", function(stdout, stderr) {
console.log("----- done -----");
// Why I never come here??????????????????????????????????
resolve();
});
});
});
});
});
答案 0 :(得分:1)
这是因为 SERVER_ID SERVER_ EXPLICIT_PERM RANK TOTAL
---------- ------- ------------- ---------- ----------
11 ZZZZZZZ 1 2 22
11 ZZZZZZZ 1 1 11
11 XXXXXXX 1 1 10
22 YYYYYYY 0 1 10
93 AVIZNER 1 1 10
不接受回调。
尝试像这样运行它:
.saveToFile
以下是关于此主题的the docs。
好听的歌btw:)