1

im not sure if this is a stupid question I'm a noob in node I'm building a youtube video download app and I'm having trouble with this block of code

   ytdl.getInfo(req.body.url)
    .then(info => {
        let title = info.videoDetails.title;
        ytdl(`https://www.youtube.com/watch?v=${v_id}`, {quality: "highestvideo"})
        .pipe(fs.createWriteStream(__dirname + `/videos/${title}.mp4`));
     console.log(title);

I'm getting error: "ReferenceError: title is not defined" when I try to console log "title" I tried making this a global variable with global.title, but it didn't make a difference i just would like to know how to reference the variable outside the scope (sorry if duplicate post)

jasonkunda00
  • 31
  • 1
  • 6
  • Declare variable outside the function and assign values inside the then scope – Dinesh Kumar DJ Sep 01 '22 at 06:17
  • @DineshKumarDJ that doesn't work. The value won't be there when you try to access it because the asynchronous code hasn't executed yet – Codebling Sep 01 '22 at 06:18
  • You don't. Everything goes in `.then()`. or use `async` / `await` – Codebling Sep 01 '22 at 06:18
  • Have you inspected `info` or `info.videoDetails.title`? `.then()` assumes `getInfo()` returns a promise, so you're waiting for it to settle/fulfill to get some response, `info` in this case. When you say _reference the variable outside the scope_, what do you mean? What are you trying to accomplish? Inner scope can access variables from outer scope, but not the other way around. More on [scope](https://dmitripavlutin.com/javascript-scope/#6-global-scope) – abgregs Sep 01 '22 at 06:32

0 Answers0