【问题标题】:nodejs variable scope issuenodejs变量范围问题
【发布时间】:2017-08-21 12:33:10
【问题描述】:

我有一个 nodejs 路由,我正在尝试使用 npm-youtube-dl 将 url 下载为 mp3。我有一个下载目录,我用 chokidar 观看正在添加的文件,当添加文件时,我保存文件的链接,下载完成后,我调用一个应该使用 res.download 响应下载 URL 的函数。当调用 sendURL 函数时,我可以清楚地看到之前保存的 url 在我 console.log 时是未定义的......知道我在这里做错了什么/我该如何解决这个问题?我猜这是一个 js 变量范围的问题?

我的代码:

var express = require('express');
var router = express.Router();
var yt = require('youtube-dl');
var fs = require('fs');
var path = require('path');
var chokidar = require('chokidar');
var downloadPath = '';

var watcher = chokidar.watch('./downloads', {
    ignored: '/^[^.]+$|\.(?!(part)$)([^.]+$)/',
    persistent: true
});

watcher.on('add', function(path) {
    console.log('added: ', path);
    this.downloadPath = path;
    console.log('saved', this.downloadPath);
});

/*
router.get('/', function(req, res, next) {
    next();
});
*/
router.get('/', function(req, res) {

    var url = 'https://soundcloud.com/astral-flowers-music/bella-flor';
    var options = ['-x', '--audio-format', 'mp3', '-o', './downloads/%(title)s.%(ext)s'];
    var video = yt.exec(url, options, {}, function exec(err, output) {

    if (err) { throw err; }
    console.log(output.join('\n'));
    sendUrl();
    });

    function sendUrl() {        
        console.log(this.downloadPath);     
        //res.download(this.downloadPath);
    }

});



module.exports = router;

【问题讨论】:

    标签: javascript node.js express youtube-dl


    【解决方案1】:

    您误用了this。如果您想在函数中使用downloadPath 变量,请从它们前面删除this.this.downloadPaththis 引用的对象上查找名为downloadPath属性,该对象与您的模块全局变量不同。

    更多:How does the "this" keyword work?


    即便如此,您仍然依赖于在任何客户端请求您的 / 路由之前调用了您的 add 回调,并且您正在返回分配给 downloadPathlast 值通过那个add 回调。我不太了解你在做什么,不知道这是否正确,但缺乏协调似乎有问题。

    【讨论】:

      猜你喜欢
      • 2020-02-29
      • 2020-06-21
      • 2020-07-24
      • 2016-08-30
      • 2011-11-21
      • 2011-04-13
      • 2011-10-20
      • 2016-06-21
      • 2011-04-10
      相关资源
      最近更新 更多