首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何修复nodejs中的“无法读取属性”包括“未定义”?[剧本]

如何修复nodejs中的“无法读取属性”包括“未定义”?[剧本]
EN

Stack Overflow用户
提问于 2019-10-10 12:26:22
回答 2查看 6.6K关注 0票数 1

我正在设置一个新的服务器,并且希望运行一个nodejs脚本来解决问题。但问题是,它在脚本启动/或运行后发布错误。

我试着在GitHub上联系“作者”,但没有回答,我也试过在其他我在线的服务器上进行测试,但它说的是同样的错误。(包括下调nodejs/npm版本的评级)

我找到的代码来自于这个GitHub页面:https://github.com/Triniayo/nodejs-discord-csgoupdate

代码语言:javascript
复制
// Requirements
const { Client } = require('discord.js');
const fs = require('fs');
const Parser = require('rss-parser');
const htmlToText = require('html-to-text');
const log = require('npmlog');

// Load Config
const cfg = require('./config.json');

// Create feeder instance
let rssParser = new Parser({
    // Renaming 'content:encoded' to 'contentHtml' because it won't be useable otherwise
    customFields: {
        item: [
            ['content:encoded', 'contentHtml']
        ]
    },
    // Setting User Agent
    headers: {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36'
    }
});

// Setting variables for the RSS output
let updateTitle;
let updateURL;
let updateContent;
let updateDate;

// Setting last update variable
let lastUpdate;

function getLastUpdate() {
    // Getting date of last update from check-update.txt file
    let dateFromFile = fs.readFileSync('check-update.txt');
    lastUpdate = dateFromFile.toString();
}

// Getting last date from check-update.txt file every 5 seconds
setInterval(getLastUpdate, 5000);

// Create Discord Bot Instance
const bot = new Client();

// Logging into Bot Account
bot.on('ready', () => {
    log.info('discord', `Logged in as ${bot.user.tag} (User ID: ${bot.user.id}) on ${bot.guilds.size} server(s)`);
    bot.user.setActivity('Fetching Updates');

    // Checking every 10 seconds if there's a new update, and if it's been posted already
    setInterval(getUpdate, 10000);
});

function getUpdate() {
    // Get current date and edit format
    let getDate = new Date();
    let date = [
        getDate.getFullYear(),
        ('0' + (getDate.getMonth() + 1)).slice(-2),
        ('0' + getDate.getDate()).slice(-2)
    ].join('-');

    // Fetching updates from CS:GO Blog
    (async () => {
        // Setting RSS Feed URL
        let feed = await rssParser.parseURL('http://blog.counter-strike.net/index.php/category/updates/feed/');

        // Setting items into variables
        feed.items.forEach(item => {
            if (item.isoDate.includes(`${date}`)) {
                updateTitle = item.title;
                updateURL = item.link;
                updateContent = item.contentHtml;
                updateDate = item.isoDate;
            }
        });

        // Converting from HTML to readable text
        let format = htmlToText.fromString(updateContent, {
            wordwrap: 130
        });

        // Limiting the update to 10 lines
        let updateNotes = format.split('\n', 10);

        if (updateDate.includes(`${date}`)) {
            if (lastUpdate !== date) {
                bot.channels.get(cfg.channelid).send("@everyone A new CS:GO Update has been released!", {
                    embed: {
                      "title": `${updateTitle}`,
                      "description": `${updateNotes.join('\n')}...\n\n[Continue reading on the CS:GO Blog](${updateURL})`,
                      "url": `${updateURL}`,
                      "color": 5478908,
                      "thumbnail": {
                        "url": "https://raw.githubusercontent.com/Triniayo/nodejs-discord-csgoupdate/master/csgo-icon.png"
                      }
                    }
                });

                // Storing date of the latest update in the check-update.txt
                fs.writeFileSync('check-update.txt', `${date}`)
            }
        } else {
            // Do nothing if update has been posted already.
        }
    })();
}

// Logging into the Bot Account
bot.login(cfg.token);

下面是错误,我是在将nodejs & npm更新到最新版本后得到的。

代码语言:javascript
复制
(node:23692) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'includes' of undefined
    at /home/mikkel/bots/csgo/app.js:87:24
    at <anonymous>
    at process._tickCallback (internal/process/next_tick.js:189:7)
(node:23692) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 13)

我不知道,这个错误意味着什么,因为我是nodejs的新手。

国家预防机制/节点的版本:

代码语言:javascript
复制
node: v8.16.1
npm: 6.12.0

我一定是改变了什么。我对javascript或nodejs没有感觉。这个脚本可以自由地放在GitHub上。

更新:编辑10/10/2019-15:28:使用日期格式做什么?-示例;在github上,它使用这种格式阅读check-update.txt : 10/23/2018 (例如)

好像它不会给我发不和谐的帖子。(如果它不这么做的话,它应该这么做)

示例:

代码语言:javascript
复制
    // Checking every 10 seconds if there's a new update, and if it's been posted already
    setInterval(getUpdate, 10000);

以下是问题所在:

代码语言:javascript
复制
            // Do nothing if update has been posted already.
        }
    })();
}

也许我应该从不和谐的开发者那里创造一个新的机器人?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-10-10 12:34:32

改变它。请求url httphttpsisoDatepubDate请求。isoDate不在提要内容中。

代码语言:javascript
复制
// Setting RSS Feed URL
let feed = await rssParser.parseURL('https://blog.counter-strike.net/index.php/category/updates/feed/');

// Setting items into variables
feed.items.forEach(item => {
  if (item.pubDate.includes(`${date}`)) {
    updateTitle = item.title;
    updateURL = item.link;
    updateContent = item.contentHtml;
    updateDate = item.pubDate || '';
  }
});
票数 0
EN

Stack Overflow用户

发布于 2019-10-10 12:37:55

您发布的错误如下:

代码语言:javascript
复制
(node:23692) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'includes' of undefined
    at /home/mikkel/bots/csgo/app.js:87:24
    at <anonymous>
    at process._tickCallback (internal/process/next_tick.js:189:7)

错误消息的第一行是说试图调用includes,或者获取对象的includes属性,但是对象没有定义。错误消息的第二行告诉您问题发生在何处;第87行(和第24列)。

第87行内容如下:

代码语言:javascript
复制
if (updateDate.includes(`${date}`)) {

因此,updateDate对象必须以某种方式未定义。综上所述,我们发现它仅在第70行的forEach循环中设置,但它位于此循环内的if语句中。

代码语言:javascript
复制
feed.items.forEach(item => {
    if (item.isoDate.includes(`${date}`)) {
        updateTitle = item.title;
        updateURL = item.link;
        updateContent = item.contentHtml;
        updateDate = item.isoDate;
    }
});

如果循环从未运行,那么updateDate将永远不会被设置。如果循环中的每个项都不包括它们的isoDate属性中的日期,那么updateDate将永远不会被设置。

因此,我们必须警惕这些案件。

通过将第87行更改为以下内容,我们可以添加将updateDate设置为某些内容的条件:

代码语言:javascript
复制
if (updateDate && updateDate.includes(`${date}`)) {
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58322866

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档