簡體   English   中英

我可以在 Node.js 和 Express 中運行 single.js 文件嗎?

[英]Can I run a single .js file in Node.js and Express?

我有一個 Node.js/Express 項目,現在我想測試它的一個文件(一個函數)。

目前,我知道這樣做的唯一方法是在index.js文件中調用此 function,並在發出npm run dev后運行文件中的所有函數。

但是,現在我只想測試一個單一的 function,所以我認為這種方法不適合。

那么誰能教我如何在 Node.js 中運行單個文件/函數?

謝謝。 我要運行的函數/文件如下,這是一個 Reddit 刮板。

const snoowrap = require("snoowrap");

async function redditCrawler(companyName, numOfMentionsToObtain) {
  const scraper = new snoowrap({
    userAgent: process.env.Reddit_userAgent,
    clientId: process.env.Reddit_clientId,
    clientSecret: process.env.Reddit_clientSecret,
    refreshToken: process.env.Reddit_refreshToken,
  });

  const subreddit = await scraper.getSubreddit("all");
  const topPosts = await subreddit.getHot({
    time: "all",
    limit: numOfMentionsToObtain,
  });

  let data = [];

  topPosts.forEach((post) => {
    // If a post doesn't have any content, just ignore it.
    if (post.title.includes(companyName) && post.selftext) {
      // If a post doesn't have a thumbnail picture, just use Reddit's logo.
      if (post.thumbnail.substr(0, 8) !== "https://") {
        post.thumbnail = "/imgs/reddit_icon.png";
      }
      data.push({
        image: post.thumbnail,
        title: post.title,
        popularity: post.score,
        content: post.selftext,
        date: post.created, // In Unix time format(in milisecond).
        platform: "Reddit",
      });
    }
  });

  return data;
}

module.exports = redditCrawler;

您可以直接通過node yourFile.js從 node 運行它

你只需要實際調用 function ,所以你想堅持redditCrawler(); 在文件的底部並可能刪除module.exports

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM