我可以从 nodejs 应用程序的 github repo 中读取文本文件吗?

问题描述

我想从某人的 github 存储库中的文本文件获取数据。 我可以使用 nodejs 来做到这一点吗(比如通过 api 调用在 octokit.js 的帮助下)。

解决方法

您可以尝试使用 node-fetch 并从原始文本中获取文本。

举个例子:

const fetch = require('node-fetch');

const getNames = () => {
  fetch('https://raw.githubusercontent.com/jeanphorn/wordlist/master/usernames.txt')
    .then(res => res.text()).then(data => {
      console.log(data);
    }).catch(err => console.log('fetch error',err));
};

或者你也可以这样试试。

const fetch = require('node-fetch');

const getNames = async() => {
  try {
    const names = await fetch('https://raw.githubusercontent.com/jeanphorn/wordlist/master/usernames.txt');
    const textData = await names.text();
    return textData;
  } catch (err) {
    console.log('fetch error',err);
  }
};

(async () => {
  const getText = await getNames();
  console.log(getText)
})();

如果您不确定如何获取原始链接。 转到 github 项目并单击要从中获取文本的文本文件,然后文本的右上角应该有一个名为 RAW 的按钮。

,

使用 Octokit,您可以使用以下方法获取文件内容:

octokit.rest.repos.getContent({
 owner,repo,path,});

参考:https://octokit.github.io/rest.js/v18#repos-get-contents