从另一个函数内部的对象中提取数据而无需写入JSON?

我正在使用discord.js和node以及一些其他软件包(例如yt-search和ytdl-core)编写具有音乐功能的Discord机器人。

我要解决的问题与下面的代码有关(newVar在测试中只是一个占位符):

        let regex = /^https/i;
        let isUrl = regex.test(checkUrl);
        let songInfo;

        if (!isUrl) {
            yts(suffix,function (err,r) {
                if(err) console.error(err);
                const videos = r.videos;
                let data = JSON.stringify(videos[0])
                fs.writeFileSync('youtube.json',data)
            })

            let newVar = require('../youtube.json');
            let {url,title} = newVar;
            songInfo = await ytdl.getInfo(newVar.url)

        } else {
            songInfo = await ytdl.getInfo(args[1]);
        }


        const song = {
            title: songInfo.title,url: songInfo.video_url,};

我要做什么,

  • 是要检查“后缀”是否为URL,如果不是,则通过yts() (yt-search)函数运行后缀,并从返回的对象中获取URL。

  • 然后通过ytdl.getInfo()函数传递该url值。

  • 它在一定程度上可以正常工作,但是写入JSON会导致一个问题,即即使重新搜索完成,它也会返回相同的URL,直到重新启动程序为止,

  • 然后,它将在执行程序时使用存储在JSON文件中的任何值重复该过程。但是,我在console.log(videos[0].url)时会得到结果,并且每个查询的值都会改变,但是如果不先写入JSON,就无法将数据传递到yts()函数之外。

有什么想法吗?

很抱歉,如果我不够具体,或者我的理解困惑,这是我的第一个“复杂”项目之一。也可能是该问题存在于模块的其他位置,但是到目前为止,我认为它在上面显示的代码中。谢谢!

LiJ86 回答:从另一个函数内部的对象中提取数据而无需写入JSON?

您可以执行一些操作以使其正确。

const getSongInfo = (url,suffix) => {
    return new Promise(async (resolve,reject) => {
        let regex = /^https/i;
        let isUrl = regex.test(url);
        if (!isUrl) {
            // netween where is the suffix variable ?
            yts(suffix,async (err,r) => {
                if(err) reject(err);
                const videos = r.videos;
                let data = JSON.stringify(videos[0]);
                // still don't know why bother save it and access it again.
                fs.writeFileSync('youtube.json',data);
                let newVar = require('../youtube.json');
                resolve(await ytdl.getInfo(newVar.url));
            });
        } else {
            resolve(await ytdl.getInfo(args[1]));
        }
    });
}


// hope the outer function is async
let songInfo = await getSongInfo(checkUrl,suffix);

const song = {
    title: songInfo.title,url: songInfo.video_url,};

请务必检查后缀变量不在范围内。

本文链接:https://www.f2er.com/2709396.html

大家都在问