Git Product home page Git Product logo

node-youtube-dl's Introduction

youtube-dl

Deprecate notice: use youtube-dl-exec instead.

Build Status npm version

Download videos from youtube in node.js using youtube-dl.

If you're only interested in downloading only from youtube, you should consider using pure Javascript youtube downloading module.

Installation

With npm do:

npm install youtube-dl

Usage

Downloading videos

const fs = require('fs')
const youtubedl = require('youtube-dl')

const video = youtubedl('http://www.youtube.com/watch?v=90AiXO1pAiA',
  // Optional arguments passed to youtube-dl.
  ['--format=18'],
  // Additional options can be given for calling `child_process.execFile()`.
  { cwd: __dirname })

// Will be called when the download starts.
video.on('info', function(info) {
  console.log('Download started')
  console.log('filename: ' + info._filename)
  console.log('size: ' + info.size)
})

video.pipe(fs.createWriteStream('myvideo.mp4'))

It will produce an output that looks like the following when ran.

Got video info
saving to T-ara - Number Nine - MV - 티아라-Seku9G1kT0c.mp4
100.00%

Resuming partially downloaded videos

const youtubedl = require('youtube-dl')
const fs = require('fs')
const output = 'myvideo.mp4'

let downloaded = 0

if (fs.existsSync(output)) {
  downloaded = fs.statSync(output).size
}

const video = youtubedl('https://www.youtube.com/watch?v=179MiZSibco',

  // Optional arguments passed to youtube-dl.
  ['--format=18'],

  // start will be sent as a range header
  { start: downloaded, cwd: __dirname })

// Will be called when the download starts.
video.on('info', function(info) {
  console.log('Download started')
  console.log('filename: ' + info._filename)

  // info.size will be the amount to download, add
  let total = info.size + downloaded
  console.log('size: ' + total)

  if (downloaded > 0) {
    // size will be the amount already downloaded
    console.log('resuming from: ' + downloaded)

    // display the remaining bytes to download
    console.log('remaining bytes: ' + info.size)
  }
})

video.pipe(fs.createWriteStream(output, { flags: 'a' }))

// Will be called if download was already completed and there is nothing more to download.
video.on('complete', function complete(info) {
  'use strict'
  console.log('filename: ' + info._filename + ' already downloaded.')
})

video.on('end', function() {
  console.log('finished downloading!')
})

It will produce an output that looks like the following when ran.

Output:

[~/nodejs/node-youtube-dl/example]$ node resume.js
Download started
filename: 1 1 1-179MiZSibco.mp4
size: 5109213
^C
[~/nodejs/node-youtube-dl/example]$ node resume.js
Download started
filename: 1 1 1-179MiZSibco.mp4
size: 5109213
resuming from: 917504
remaining bytes: 4191709
finished downloading

Getting video information

const youtubedl = require('youtube-dl')

const url = 'http://www.youtube.com/watch?v=WKsjaOqDXgg'
// Optional arguments passed to youtube-dl.
const options = ['--username=user', '--password=hunter2']

youtubedl.getInfo(url, options, function(err, info) {
  if (err) throw err

  console.log('id:', info.id)
  console.log('title:', info.title)
  console.log('url:', info.url)
  console.log('thumbnail:', info.thumbnail)
  console.log('description:', info.description)
  console.log('filename:', info._filename)
  console.log('format id:', info.format_id)
})

Running that will produce something like

id: WKsjaOqDXgg
title: Ace Rimmer to the Rescue
url: http://r5---sn-p5qlsn7e.c.youtube.com/videoplayback?ms=au&ip=160.79.125.18&cp=U0hWTFVQVl9FTENONl9NSlpDOjgtU1VsODlkVmRH&id=58ab2368ea835e08&source=youtube&expire=1377558202&factor=1.25&key=yt1&ipbits=8&mt=1377534150&itag=34&sver=3&upn=-rGWz2vYpN4&fexp=912306%2C927900%2C919395%2C926518%2C936203%2C913819%2C929117%2C929121%2C929906%2C929907%2C929922%2C929127%2C929129%2C929131%2C929930%2C925726%2C925720%2C925722%2C925718%2C929917%2C906945%2C929919%2C929933%2C912521%2C932306%2C913428%2C904830%2C919373%2C930803%2C908536%2C904122%2C938701%2C936308%2C909549%2C900816%2C912711%2C904494%2C904497%2C900375%2C906001&sparams=algorithm%2Cburst%2Ccp%2Cfactor%2Cid%2Cip%2Cipbits%2Citag%2Csource%2Cupn%2Cexpire&mv=m&burst=40&algorithm=throttle-factor&signature=ABD3A847684AD9B39331E567568D3FA0DCFA4776.7895521E130A042FB3625A17242CE3C02A4460B7&ratebypass=yes
thumbnail: https://i1.ytimg.com/vi/WKsjaOqDXgg/hqdefault.jpg
description: An old Red Dwarf eposide where Ace Rimmer saves the Princess Bonjella.
filename: Ace Rimmer to the Rescue-WKsjaOqDXgg.flv
format id: 34

You can use an array of urls to produce an array of response objects with matching array index (e.g. the 1st response object will match the first url etc...)

const youtubedl = require('youtube-dl')

const url1 = 'http://www.youtube.com/watch?v=WKsjaOqDXgg'
const url2 = 'https://vimeo.com/6586873'

youtubedl.getInfo([url1, url2], function(err, info) {
  if (err) throw err

  console.log('title for the url1:', info[0].title)
  console.log('title for the url2:', info[1].title)
})

Using a proxy

const youtubedl = require('youtube-dl')

const video = youtubedl('http://www.youtube.com/watch?v=90AiXO1pAiA',
  // Optional arguments passed to youtube-dl.
  ['--proxy', 'http://ip:port'],

Downloading subtitles

const youtubedl = require('youtube-dl')
const url = 'https://youtu.be/PizwcirYuGY'

const options = {
  // Write automatic subtitle file (youtube only)
  auto: false,
  // Downloads all the available subtitles.
  all: false,
  // Subtitle format. YouTube generated subtitles
  // are available ttml or vtt.
  format: 'ttml',
  // Languages of subtitles to download, separated by commas.
  lang: 'en',
  // The directory to save the downloaded files in.
  cwd: __dirname,
}

youtubedl.getSubs(url, options, function(err, files) {
  if (err) throw err

  console.log('subtitle files downloaded:', files)
})

Downloading thumbnails

const youtubedl = require('youtube-dl')
const url = 'https://youtu.be/PizwcirYuGY'

const options = {
  // Downloads available thumbnail.
  all: false,
  // The directory to save the downloaded files in.
  cwd: __dirname,
}

youtubedl.getThumbs(url, options, function(err, files) {
  if (err) throw err

  console.log('thumbnail file downloaded:', files)
})

For more usage info on youtube-dl and the arguments you can pass to it, do youtube-dl -h or go to the youtube-dl documentation.

Downloading playlists

const path = require('path')
const fs   = require('fs')
const youtubedl = require('youtube-dl')

function playlist(url) {

  'use strict'
  const video = youtubedl(url)

  video.on('error', function error(err) {
    console.log('error 2:', err)
  })

  let size = 0
  video.on('info', function(info) {
    size = info.size
    let output = path.join(__dirname + '/', size + '.mp4')
    video.pipe(fs.createWriteStream(output))
  })

  let pos = 0
  video.on('data', function data(chunk) {
    pos += chunk.length
    // `size` should not be 0 here.
    if (size) {
      let percent = (pos / size * 100).toFixed(2)
      process.stdout.cursorTo(0)
      process.stdout.clearLine(1)
      process.stdout.write(percent + '%')
    }
  })

  video.on('next', playlist)
}

playlist('https://www.youtube.com/playlist?list=PLEFA9E9D96CB7F807')

Note node-youtube-dl does not currently support playlist urls with the "list" format:

https://www.youtube.com/watch?v=<video-id>&list=<playlist id>

Please use instead the equivalent "playlist" format as the example below:

https://www.youtube.com/playlist?list=<playlist id>

The following snippet could be of use when making this format conversion.

function toSupportedFormat(url) {
    if (url.includes("list=")) {
        var playlistId = url.substring(url.indexOf('list=') + 5);
        return "https://www.youtube.com/playlist?list=" + playlistId;
    }
    return url;
}

var url = "https://www.youtube.com/watch?v=shF8Sv-OswM&list=PLzIUZKHPb1HbqsPMIFdE0My54iektZrNU"
url = toSupportedFormat(url);
console.log(url) // "https://www.youtube.com/playlist?list=PLzIUZKHPb1HbqsPMIFdE0My54iektZrNU"

Getting the list of extractors

const youtubedl = require('youtube-dl')

youtubedl.getExtractors(true, function(err, list) {
  console.log('Found ' + list.length + ' extractors')

  for (let i = 0 i < list.length i++) {
    console.log(list[i])
  }
})

Will print something like

Found 521 extractors
1up.com
220.ro
24video
3sat

Getting the binary path

const youtubedl = require('youtube-dl')

console.log(youtubedl.getYtdlBinary())

Changing the binary path

const path = require('path')
const youtubedl = require('youtube-dl')

const customBinaryPath = path.resolve('custom/path/to-binary')

youtubedl.setYtdlBinary(customBinaryPath)

Call the youtube-dl binary directly

This module doesn't have youtube-dl download the video. Instead, it uses the url key from the --dump-json CLI option to create a node stream. That way, it can be used like any other node stream.

If that, or none of the above support your use case, you can use youtubedl.exec() to call youtube-dl however you like.

const youtubedl = require('youtube-dl')

youtubedl.exec(url, ['-x', '--audio-format', 'mp3'], {}, function(err, output) {
  if (err) throw err

  console.log(output.join('\n'))
})

Update

Since the youtube-dl binary is updated regularly, you can run npm run update to check for and download any updates for it. You can also require youtube-dl/lib/downloader in your app if you'd like to place youtube-dl binary in a specific directory and control when it gets updates.

const downloader = require('youtube-dl/lib/downloader')

downloader('path/to-binary', function error(err, done) {
  'use strict'
  if (err) throw err

  console.log(done)
})

This script parses a couple of flags from argv:

  • --platform=windows forces downloading the Windows version of youtube-dl.
  • --overwrite overwrites the existing youtube-dl executable if it exists.

Update (promise version)

If you are using promises there's now a promise version, if you don't pass a function as second argument:

const downloader = require('youtube-dl/lib/downloader')

downloader('path/to-binary')
.then((message) => {
    console.log(message);
}).catch((err) => {
    console.log("err", err);
    exit(1);
});

Environment Variables

Youtube-dl looks for certain environment variables to aid its operations. If Youtube-dl doesn't find them in the environment during the installation step, a lowercased variant of these variables will be used from the npm config or yarn config.

  • YOUTUBE_DL_DOWNLOAD_HOST - overwrite URL prefix that is used to download the binary file of Youtube-dl. Note: this includes protocol and might even include path prefix. Defaults to https://yt-dl.org/downloads/latest/youtube-dl.

Tests

Tests are written with vows

npm test

License

MIT

node-youtube-dl's People

Contributors

assetkid avatar barrycarlyon avatar bartronicus avatar boulosda avatar brunobg avatar btmdave avatar coderaiser avatar coriou avatar dodo avatar dstftw avatar eragonj avatar fent avatar fredericgermain avatar jaimemf avatar jaysalvat avatar jeremyplease avatar kennylbj avatar kikobeats avatar kr4ssi avatar logikaljay avatar navispeed avatar optikfluffel avatar przemyslawpluta avatar qhadron avatar rafaelkr avatar saginadir avatar skiptirengu avatar telno avatar tifroz avatar walheresq avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

node-youtube-dl's Issues

Unhandled 'error' event -> ENOENT error issues

What I am doing is downloading an entire youtube playlist. youtube-dl works perfectly for me with some videos, but breaks with others. Here is an example output:

--------------------------------------------------------
[INFO] GATHERING VIDEOS FROM SELECTED PLAYLIST
--------------------------------------------------------
[Progressive House] - Hellberg & Rich Edwards - Ashes (feat. Danyka Nadeau) [Monstercat Release]
---Complete 
[Dubstep] - Varien - Whispers in the Mist (feat. Aloma Steele) [Monstercat Release]
---Complete 
[Minimal / Trance] - Laszlo - Messiah [Monstercat Release]

events.js:72
        throw er; // Unhandled 'error' event
              ^
Error: ENOENT, open '/home/ubuntu/workspace/mp4s/[Minimal / Trance] - Laszlo - Messiah [Monstercat Release].mp4'

Here is a portion of my code:

    var size = 0;
    video.on('error', function(err) {
        console.log("Error 2:  " + err);
        return 0;
    });

    video.on('info', function(info) {
        size = info.size;
        var output = path.join(__dirname + "/mp4s", info.title + ".mp4");
        video.pipe(fs.createWriteStream(output));
    });

Now, I am not sure if any of you have ran into this issue.
Any help would be appreciated.

EDIT: The video in question is this video

Fails with non-Youtube sites

When I try to do .getInfo for an Vimeo video, it fails. Even though you mention in the readme that this supports many more sites (like youtube-dl itself does), it looks like yours isn't made to work with any other sites.

Two places where I know it messes up is on line 95, where it defaults to http://www.youtube.com/watch?v= if a playlist isn't detected, and when that is fixed, the parsing of info doesn't seem to work.

I'm testing against the Vimeo video https://vimeo.com/6586873

Is there any way to get available video formats ?

By the way , I tried to tweak the youtube-dl.js file by adding "-F" in

args = [
      '--get-id'
    , '--get-url'
    , '--get-title'
    , '--get-thumbnail'
    , '--get-filename'
    , '--get-format'
    , '--get-description'
    , '-F'
  ].concat(args);

But it breaks the output !

Installation Error on Windows

Tryin' to install youtube-dl via npm install youtube-dl getting the following error log:

D:\workspace_js\youtube-music-downloader-service>npm install youtube-dl
npm http GET https://registry.npmjs.org/youtube-dl
npm http 304 https://registry.npmjs.org/youtube-dl

> [email protected] preinstall D:\workspace_js\youtube-music-downloader-service\node_modules\youtube-dl
> node ./scripts/download.js

Downloading latest youtube-dl
Downloaded youtube-dl 2014.09.16.1

D:\workspace_js\youtube-music-downloader-service\node_modules\youtube-dl\scripts\download.js:17
  throw err;
        ^
Error: write ECONNABORTED
    at errnoException (net.js:901:11)
    at Socket._write (net.js:643:26)
    at doWrite (_stream_writable.js:221:10)
    at writeOrBuffer (_stream_writable.js:211:5)
    at Socket.Writable.write (_stream_writable.js:180:11)
    at Socket.write (net.js:613:40)
    at write (_stream_readable.js:583:24)
    at flow (_stream_readable.js:592:7)
    at EncryptedStream.pipeOnReadable (_stream_readable.js:624:5)
    at EncryptedStream.EventEmitter.emit (events.js:92:17)
npm ERR! weird error 8
npm ERR! not ok code 0

Issues with the downloads

It looks like there are issues with the way downloads are being handled since > v1.3.6. It works fine as long as all you're downloading is the video file only.

var video = ytdl('https://www.youtube.com/watch?v=179MiZSibco', ['--max-quality=22']);

var size = 0;
video.on('info', function(info) {
  size = info.size;
  console.log('Got video info');
  console.log('saving to ' + info.filename);
  var output = path.join('/target/to/directory/', info.filename);
  video.pipe(fs.createWriteStream(output));
});

The moment you specify additional options like downloading closed captions with the video:

var video = ytdl('https://www.youtube.com/watch?v=179MiZSibco', ['--max-quality=22', '--write-srt', '--srt-lang=en']);

Only the video is being downloaded into the specified location while the closed caption file is being downloaded in to the local directory.

This works as expected when the arguments are passed to the ./bin/youtube-dl directly.

unable to extract comment count; please report this issue on http://yt-dl.org/bug

Some sites aren't working. youtube-dl command line outputs a warning which shouldn't cause an error as it does output the json but node-youtube-dl does produce an error and doesn't create the info object.

python "C:\Users\...\AppData\Roaming\node_modules\youtube-dl\bin\youtube-dl" --dump-json  http://www.pornhub.com/view_video.php?viewkey=925419364 > json.js

gives the error

WARNING: unable to extract comment count; please report this issue on http://yt-dl.org/bug

but it produces the json anyways which does contain the relevant stream url

{
    "display_id": "925419364",
    "extractor": "PornHub",
    "stitle": "Nicki Minaj - Anaconda (porn edit)",
    "format": "720P-1500K",
    ...
    "title": "Nicki Minaj - Anaconda (porn edit)",
    "url": "http://cdn2b.video.pornhub.phncdn.com/videos/201502/22/45224141/720P_1500K_45224141.mp4?rs=200&ri=2500&s=1427050269&e=1427057469&h=333057563d7ca8ffa781722dc75648e7",
    "extractor_key": "PornHub",
    ...
}

but the outputed error is reproduced in node app and info object is null

var video = youtubedl.getInfo(url,... function(err, info){
    // err => [Error: : unable to extract comment count; please report this issue on http://yt-dl.org/bug]
    // info => null
}

Cannot download Dailymotion video using current version of youtube-dl binary

The current youtube-dl in bin folder is 2013.05.14, but when I try to download a dailymotion video:

http://www.dailymotion.com/video/x11x4c6_kelly-osbourne-announces-her-engagement-to-matthew-mosshart_people

It gives me the following error:

Error: : unable to extract uploader nicknam
    at Socket.<anonymous> (/Users/user/projects/ytdl-test/node_modules/youtube-dl/lib/youtube-dl.js:181:15)
    at Socket.EventEmitter.emit (events.js:95:17)
    at Socket.<anonymous> (_stream_readable.js:710:14)
    at Socket.EventEmitter.emit (events.js:92:17)
    at emitReadable_ (_stream_readable.js:382:10)
    at emitReadable (_stream_readable.js:378:5)
    at readableAddChunk (_stream_readable.js:143:7)
    at Socket.Readable.push (_stream_readable.js:113:10)
    at Pipe.onread (net.js:511:21)

But after I manually update the youtube-dl binary to the latest 2013.07.10, it works fine.

Pure JS implementation for Cordova

Cordova enables HTML/JS/CSS on iOS, Android, etc. (http://cordova.apache.org).

CORS restrictions do not apply in this case. How much work do you think it would take to offer non-node implementation of ytdl (just the part getInfo to get the stream urls, not the downloading). Is that even possible ?

Error when trying to use example

I tried to use youtube-dl module to download video, but upon installing the module and testing the example I get an error:

events.js:72
throw er; // Unhandled 'error' event
^
Error: spawn ENOENT
at errnoException (child_process.js:975:11)
at Process.ChildProcess._handle.onexit (child_process.js:766:34)

Help plaese? ^-^

Include video id and format

It would be great to have the full set of video meta data available, currently --get-id and --get-format are missing

Regex doesn't match anymore

The regex doesn't match anymore with the latest version of youtube-dl (add MiB), here is the updated regex:

var regex = /(\d+\.\d)% of (\d+\.\d+\w)MiB at\s+([^\s]+) ETA ((\d|-)+:(\d|-)+)/;

Progress Event

Don't Emit the Progress Event!
Line 143
replace it with:

youtubedl.stdout.setEncoding('utf8');
//youtubedl.stdout.pipe(line);
youtubedl.stdout.on('data', function(data) {

--extract-audio

how do we use --extract-audio option that exists in youtube-dl?

Any reason duration is not available from getInfo()?

Looking at the source code there is a comment stating "Arguments we dont want users to use with youtube-dl because they will break the module" and the code proceeds to exclude the --get-duration argument.

I did a quick test using http://vimeo.com/channels/staffpicks/115680769, and the duration was actually returned ok (though the corresponding string 9:56 is later mis-categorized as filename in the result hash)

I would submit a PR to allow the duration among the allowable arguments (and categorize the results appropriately) - but I figured I would check first in case there is something I am missing: I only tested with this one URL after all.

feature supported

Does it support following features?

  1. download video from other sources instead?
  2. will it work for resume download in case internet connection interrupted?

Can’t npm install youtube-dl on Mac yosemite 10.10.1

execute command and error message list below.

$  npm -v
2.1.17

$  node -v
v0.10.35

$   npm install youtube-dl
-
> [email protected] preinstall /Users/taian/tmp/node_modules/youtube-dl
> node ./scripts/download.js

Downloading latest youtube-dl

/Users/taian/tmp/node_modules/youtube-dl/scripts/download.js:19
  throw err;
        ^
Error: CERT_UNTRUSTED
    at SecurePair.<anonymous> (tls.js:1381:32)
    at SecurePair.emit (events.js:92:17)
    at SecurePair.maybeInitFinished (tls.js:980:10)
    at CleartextStream.read [as _read] (tls.js:472:13)
    at CleartextStream.Readable.read (_stream_readable.js:341:10)
    at EncryptedStream.write [as _write] (tls.js:369:25)
    at doWrite (_stream_writable.js:226:10)
    at writeOrBuffer (_stream_writable.js:216:5)
    at EncryptedStream.Writable.write (_stream_writable.js:183:11)
    at write (_stream_readable.js:602:24)
npm ERR! Darwin 14.0.0
npm ERR! argv "node" "/usr/local/bin/npm" "install" "youtube-dl"
npm ERR! node v0.10.35
npm ERR! npm  v2.1.17
npm ERR! code ELIFECYCLE

npm ERR! [email protected] preinstall: `node ./scripts/download.js`
npm ERR! Exit status 8
npm ERR!
npm ERR! Failed at the [email protected] preinstall script 'node ./scripts/download.js'.
npm ERR! This is most likely a problem with the youtube-dl package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     node ./scripts/download.js
npm ERR! You can get their info via:
npm ERR!     npm owner ls youtube-dl
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR!     /Users/taian/tmp/npm-debug.log

no subtitles downloaded

There seems to be an issues with the subtitles at the moment. With this no subtitles are downloaded only the video.

var fs = require('fs'),
   youtubedl = require('youtube-dl'),
   video = youtubedl('https://youtu.be/PizwcirYuGY', ['--max-quality=18', '--sub-lang=en', '--write-sub'], { cwd: __dirname });

video.pipe(fs.createWriteStream('PizwcirYuGY.mp4'))

But when you go directly video and subtitles are downloaded as expected.

./youtube-dl/bin/youtube-dl https://youtu.be/PizwcirYuGY --max-quality=18 --sub-lang=en --write-sub

Unable to download just audio

When running youtubedl(url, ['-x']) I get back a video file due to #75 and related changes to adding a default for -f/--format if undefined.

-x is an alias of --extract-audio

Remove check platform.

Dear Developer.

I check your code I saw line code check platform "isWin", I think it is unnecessary because your module can working in linux platform but when I install in linux I must fix your code to compatible.

Can you remove this lines below in next version?

// Check if win.
var isWin = /^win/.test(process.platform);
if (isWin) { opt = [process.env.PYTHON || 'python', [file].concat(args)]; }

and change it to

opt = [process.env.PYTHON || 'python', [file].concat(args)];

Best regard.

Phong Dao

permission error on npm install

"npm install" works as root, as normal user however this happens:

[email protected] preuninstall /home/acechadores/public_git/node/node_modules/youtube-dl
node ./scripts/download.js

node.js:183
throw e; // process.nextTick error, or 'error' event on first tick
^
Error: ENOENT, No such file or directory '/usr/local/bin/youtube-dl'
at Object.unlinkSync (fs.js:432:18)
at Object. (/home/acechadores/public_git/node/node_modules/youtube-dl/scripts/download.js:48:10)
at Object. (/home/acechadores/public_git/node/node_modules/youtube-dl/scripts/download.js:50:4)
at Module._compile (module.js:423:26)
at Object..js (module.js:429:10)
at Module.load (module.js:339:31)
at Function._load (module.js:298:12)
at Array. (module.js:442:10)
at EventEmitter._tickCallback (node.js:175:26)
npm ERR! forced, continuing Error: [email protected] preuninstall: node ./scripts/download.js
npm ERR! forced, continuing sh "-c" "node ./scripts/download.js" failed with 1
npm ERR! forced, continuing at ChildProcess. (/usr/local/lib/node_modules/npm/lib/utils/exec.js:49:20)
npm ERR! forced, continuing at ChildProcess.emit (events.js:67:17)
npm ERR! forced, continuing at ChildProcess.onexit (child_process.js:246:12)

[email protected] preinstall /home/acechadores/public_git/node/node_modules/youtube-dl
node ./scripts/download.js

fs.js:416
return binding.symlink(destination, path);
^
Error: EACCES, Permission denied
at Object.symlinkSync (fs.js:416:18)
at IncomingMessage. (/home/acechadores/public_git/node/node_modules/youtube-dl/scripts/download.js:44:21)

at IncomingMessage.emit (events.js:81:20)
at HTTPParser.onMessageComplete (http.js:133:23)
at CleartextStream.ondata (http.js:1228:22)
at CleartextStream._push (tls.js:331:27)
at SecurePair.cycle (tls.js:608:20)
at EncryptedStream.write (tls.js:124:13)
at Socket.ondata (stream.js:36:26)
at Socket.emit (events.js:64:17)

npm ERR! forced, continuing Error: [email protected] preinstall: node ./scripts/download.js
npm ERR! forced, continuing sh "-c" "node ./scripts/download.js" failed with 1
npm ERR! forced, continuing at ChildProcess. (/usr/local/lib/node_modules/npm/lib/utils/exec.js:49:20)
npm ERR! forced, continuing at ChildProcess.emit (events.js:67:17)
npm ERR! forced, continuing at ChildProcess.onexit (child_process.js:246:12)
[email protected] ./node_modules/youtube-dl
-sh-3.2$ npm install youtube-dl

[email protected] preuninstall /home/acechadores/public_git/node/node_modules/youtube-dl
node ./scripts/download.js

[email protected] preinstall /home/acechadores/public_git/node/node_modules/youtube-dl
node ./scripts/download.js

fs.js:416
return binding.symlink(destination, path);
^
Error: EACCES, Permission denied
at Object.symlinkSync (fs.js:416:18)
at IncomingMessage. (/home/acechadores/public_git/node/node_modules/youtube-dl/scripts/download.js:44:21)
at IncomingMessage.emit (events.js:81:20)
at HTTPParser.onMessageComplete (http.js:133:23)
at CleartextStream.ondata (http.js:1228:22)
at CleartextStream._push (tls.js:331:27)
at SecurePair.cycle (tls.js:608:20)

at EncryptedStream.write (tls.js:124:13)
at Socket.ondata (stream.js:36:26)
at Socket.emit (events.js:64:17)

npm ERR! error installing [email protected] Error: [email protected] preinstall: node ./scripts/download.js
npm ERR! error installing [email protected] sh "-c" "node ./scripts/download.js" failed with 1
npm ERR! error installing [email protected] at ChildProcess. (/usr/local/lib/node_modules/npm/lib/utils/exec.js:49:20)
npm ERR! error installing [email protected] at ChildProcess.emit (events.js:67:17)
npm ERR! error installing [email protected] at ChildProcess.onexit (child_process.js:246:12)

[email protected] preuninstall /home/acechadores/public_git/node/node_modules/youtube-dl
node ./scripts/download.js

npm ERR! [email protected] preinstall: node ./scripts/download.js
npm ERR! sh "-c" "node ./scripts/download.js" failed with 1
npm ERR!
npm ERR! Failed at the [email protected] preinstall script.
npm ERR! This is most likely a problem with the youtube-dl package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR! node ./scripts/download.js
npm ERR! You can get their info via:
npm ERR! npm owner ls youtube-dl
npm ERR! There is likely additional logging output above.
npm ERR!
npm ERR! System Linux 2.6.18-238.19.1.el5
npm ERR! command "node" "/usr/local/bin/npm" "install" "youtube-dl"
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR! /home/acechadores/public_git/node/npm-debug.log
npm not ok

spawn ENOENT and permissions issue

Hi, I've tried to install using npm install youtube-dl, but installing locally gives me:

events.js:72
        throw er; // Unhandled 'error' event
              ^
Error: spawn ENOENT
    at errnoException (child_process.js:980:11)
    at Process.ChildProcess._handle.onexit (child_process.js:771:34)

I tried to install globally, but I have to sudo for it to install. However, when I try to access youtube-dl from the command line, I get:

python: can't open file '/usr/bin/youtube-dl': [Errno 13] Permission denied unless I use 'sudo' and I still get the same spawn error as above.

Any suggestions to install this?

Thank you!

Bug with higher video resolutions

Hello,
I was trying to download a video with highest quality (2160p) and I was not possible.

I took a look to your code and found 2 little bugs in regexp parsing video resolutions. Now, youtube returns resolutions 1280x720 and 720p but with higher resulutions, only returns 2160p

Bugfixes:
line 132: var resolutionRegex = /([0-9]+ - [0-9]+x[0-9]+)/;
bugfix: var resolutionRegex = /([0-9]+ - ([0-9]+x[0-9]+)|\d+p)/;

line 183: var formatsRegex = /^(\d+)\s+([a-z0-9]+)\s+(\d+x\d+|d+p|audio only)/;
bugfix: var formatsRegex = /^(\d+)\s+([a-z0-9]+)\s+(\d+x\d+|\d+p|audio only)/;

I hope it was helpfull

npm installation issue

[email protected] preuninstall /home/acechadores/public_git/node/node_modules/youtube-dl
node ./scripts/download.js

node.js:183
throw e; // process.nextTick error, or 'error' event on first tick
^
Error: ENOENT, No such file or directory '/usr/local/bin/youtube-dl'
at Object.unlinkSync (fs.js:432:18)
at Object. (/home/acechadores/public_git/node/node_modules/youtube-dl/scripts/download.js:48:10)
at Object. (/home/acechadores/public_git/node/node_modules/youtube-dl/scripts/download.js:50:4)
at Module._compile (module.js:423:26)
at Object..js (module.js:429:10)
at Module.load (module.js:339:31)
at Function._load (module.js:298:12)
at Array. (module.js:442:10)
at EventEmitter._tickCallback (node.js:175:26)
npm ERR! error installing [email protected] Error: [email protected] preuninstall: node ./scripts/download.js

npm ERR! error installing [email protected] sh "-c" "node ./scripts/download.js" failed with 1
npm ERR! error installing [email protected] at ChildProcess. (/usr/local/lib/node_modules/npm/lib/utils/exec.js:49:20)
npm ERR! error installing [email protected] at ChildProcess.emit (events.js:67:17)
npm ERR! error installing [email protected] at ChildProcess.onexit (child_process.js:246:12)

Maybe check if file exists before fs.unlink in download.js:48? I would try to fix myself but I don't know how to build npm packages.

stdout maxBuffer exceeded

how can I increase the buffer size?
I got this when downloading a playlist.
error 2: [Error: stdout maxBuffer exceeded.]

Sample code does not run

fs and youtubedl are both included before this code chunk. It runs up to this point, and then throws the error I included below. I'm using windows with git bash. I'm really not sure how to move past this, or how to troubleshoot.

var video = youtubedl('http://www.youtube.com/watch?v=90AiXO1pAiA',
          // optional arguments passed to youtube-dl
          ['--max-quality=18']);

        // will be called when the download starts
        video.on('info', function(info) {
          console.log('Download started');
          console.log('filename: ' + info.filename);
          console.log('size: ' + info.size);
        });

        video.pipe(fs.createWriteStream('myvideo_' + Date.now() + '.mp4'));
events.js:72
        throw er; // Unhandled 'error' event
              ^
Error: spawn ENOENT
    at errnoException (child_process.js:980:11)
    at Process.ChildProcess._handle.onexit (child_process.js:771:34)

Error when trying to use 1st example

Got this error....

events.js:72
        throw er; // Unhandled 'error' event
              ^
Error: spawn ENOENT

I m using ubuntu .... I installed using npm install -g .

-f "[filesize>10M]" gives the error "requested format not available"

I'm trying to get a video with filesize restriction, as is possible with the -f "[filesize<100M]" option. But the node-youtube-dl always gives the error "requested format not available".

The standalone command that node-youtube-dl runs internally actually does output the JSON

python "C:\...\node_modules\youtube-dl\bin\youtube-dl" --dump-json -f "[filesize<100M]" http://youtu.be/...

outputs this JSON, which most probably does contain the requested format but node-youtube-dl still gives that error.

I'm using it like this in my node app:

var video = youtubedl.getInfo(url, [ '-f "[filesize<100M]"' ] , function(err, info) { // err : "requested format not available" } );

It works fine otherwise.

PS: Even -f "[filesize>10M]" gives the same error.

--format=bestvideo+bestaudio is not working

If we use bestvideo+bestaudio directly using youtube-dl command line, video and audio are merged (if you have ffmpeg installed).

Often used for DASH youtube videos (1080p)

Module is not working

Started tests and it didn't pass.

vows ./test/*.js --spec

♢ download

a video with format specified
✗ data returned
Error: spawn ENOENT
at errnoException (child_process.js:1000:11)
at Process.ChildProcess._handle.onexit (child_process.js:791:34)
✗ file was downloaded
Error: spawn ENOENT
at errnoException (child_process.js:1000:11)
at Process.ChildProcess._handle.onexit (child_process.js:791:34)
a video with no format specified
✗ data returned
Error: spawn ENOENT
at errnoException (child_process.js:1000:11)
at Process.ChildProcess._handle.onexit (child_process.js:791:34)
✗ file was downloaded
Error: spawn ENOENT
at errnoException (child_process.js:1000:11)
at Process.ChildProcess._handle.onexit (child_process.js:791:34)
a video with subtitles
✗ subtitles were downloaded
Error: spawn ENOENT
at errnoException (child_process.js:1000:11)
at Process.ChildProcess._handle.onexit (child_process.js:791:34)

♢ getExtractors

Suggestion : spawn instead of execFile

I use node-youtube-dl to display videos in an express app. After a few calls callbacks are not executed anymore (read someting about pipes being full).
I made a very simple implementation with spawn that should have the same behaviour as execFile and that does not have the same issue:

var spawn = require('child_process').spawn;

var getRessource = function(url, callback) {
    var ytdl = spawn('youtube-dl', [url, '--get-url']),
    error = null,
    info = null;
    ytdl.stdout.on('data', function(data) {
        info = data.toString();
    });
    ytdl.stderr.on('data', function(data) {
        error = data.toString().slice(7);
    });
    ytdl.on('exit', function(code) {
        callback(error, info);
    });
};

I believe it's worth giving a shot.

Nice work ;)

Missing list of extractors (feature request)

I need an API to get the available list of extractors youtube-dl --extractor

Happy to submit a PR to make it happen - but again checking with you first in case this is already underway, or in case you would like to communicate some implementation preference ahead of time.

Proxy Support

Hi there

I work on a script to download YT videos, that are blocked in my country, over an ssh-tunnled proxy.
I tried your example download script with the option "--proxy=127.0.0.1:8000", but it throws an error:

events.js:72
        throw er; // Unhandled 'error' event
              ^
Error: status code 403
    at Request.<anonymous> (/root/nodejs/node_modules/youtube-dl/lib/youtube-dl.js:65:30)
    at Request.EventEmitter.emit (events.js:95:17)
    at Request.onResponse (/root/nodejs/node_modules/youtube-dl/node_modules/request/request.js:924:10)
    at ClientRequest.g (events.js:180:16)
    at ClientRequest.EventEmitter.emit (events.js:95:17)
    at HTTPParser.parserOnIncomingClient [as onIncoming] (http.js:1688:21)
    at HTTPParser.parserOnHeadersComplete [as onHeadersComplete] (http.js:121:23)
    at CleartextStream.socketOnData [as ondata] (http.js:1583:20)
    at CleartextStream.read [as _read] (tls.js:511:12)
    at CleartextStream.Readable.read (_stream_readable.js:320:10)

When i call youtube-dl from the console it works flawless.
"youtube-dl --proxy http://127.0.0.1:8000/ https://www.youtube.com/watch?v=Lle-q-0SL_c"

Would it be possible to implant proxy support?

Greetings

Pass content-range info to youtubedl to make a seekable player

I'm trying to make a youtube stream server based on youtube-dl that would enable seeking though the video. To achieve this I pipe the server's response object to the stream. I wondered if it was possible to make partial requests (206) to the server and pass the request's content-range info to youtubedl in order to achieve back and forth seeking. I (nearly) managed to do it on a stream based on a mp4 ressource (nearly, the server ends up not responding after a while...) but can't figure if its possible with youtubedl.

Help and/or feature whould be much appreciated!

Jonathan

PS: The callback in the server once I've got the stream:

function(stream, info){
var total = stream.headers['content-range'] ? _.last(stream.headers['content-range'].split('/')) : stream.headers['content-length'];
var range = req.headers.range;
var positions;
var start;
var end;
var chunksize;
var statusCode = 200;
var config = {
"Accept-Ranges": "bytes",
"Content-Type": info.type, //'video/mp4'
"Content-Length": total,
"Transfer-encoding" : 'chunked'
}
if(range)
{
statusCode = 206;
positions = range.replace(/bytes=/, "").split("-");
start = parseInt(positions[0], 10);
end = positions[1] ? parseInt(positions[1], 10) : total - 1;
chunksize = (end-start) + 1;
config["Content-Range"] = "bytes " + start + "-" + end + "/" + total;
config["Content-Length"] = chunksize;
}
res.writeHead(statusCode, config);
stream.pipe(res);
});

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.