download.js
// 下載視頻
const fs = require('fs');
const http = require('http');
const config = require('./config');
function getVideoData(url, encoding) {
return new Promise((resolve, reject) => {
let req = http.get(url, function (res) {
let result = ''
encoding && res.setEncoding(encoding)
res.on('data', function (d) {
result += d
})
res.on('end', function () {
resolve(result)
})
res.on('error', function (e) {
reject(e)
})
})
req.end()
})
}
function savefileToPath(fileName, fileData) {
let fileFullName = `${config.savePath}/${fileName}.mp4`
return new Promise((resolve, reject) => {
fs.writeFile(fileFullName, fileData, 'binary', function (err) {
if (err) {
console.log('savefileToPath error:', err)
}
resolve('已下載')
})
})
}
async function downloadVideo(video) {
// 判斷視頻文件是否已經(jīng)下載
if (!fs.existsSync(`${config.savePath}/${video.title}.mp4`)) {
await getVideoData(video.url, 'binary').then(fileData => {
console.log('下載視頻中:', video.title)
savefileToPath(video.title, fileData).then(res =>
console.log(`${res}: ${video.title}`)
)
})
} else {
console.log(`視頻文件已存在:${video.title}`)
}
}
module.exports = downloadVideo
本站僅提供存儲(chǔ)服務(wù),所有內(nèi)容均由用戶發(fā)布,如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請(qǐng)
點(diǎn)擊舉報(bào)。