繁体   English   中英

如何在 node.js 中使用这个 javascript 库?

[英]How do I utilize this javascript library in node.js?

我对 node.js 比较陌生,我试图利用 javascript 库没有任何成功。

库本身是psn-api

要设置使用,我有:

  1. 本地安装node.js
  2. 创建了我的项目文件夹
  3. npm init并成功创建 package.json
  4. Ran npm install i -s psn-api已成功将 psn-api 安装到我的节点模块中的项目文件夹并更新了 package.json 中的依赖项。
  5. 我已经从 psn-api github(见下文)复制了示例代码,并在我的项目文件夹中保存为 index.ts 文件。
  6. 我运行npx tsc --init生成我的 tsconfig.json 文件
  7. 我运行npx tsc index.ts编译成 index.js
  8. 我运行节点 index.js

示例代码(index.ts):

import * as fs from "fs";

import type { Trophy } from "psn-api";
import {
  exchangeCodeForAccessToken,
  exchangeNpssoForCode,
  getTitleTrophies,
  getUserTitles,
  getUserTrophiesEarnedForTitle,
  makeUniversalSearch,
  TrophyRarity
} from "psn-api";

async function main() {
  // 1. Authenticate and become authorized with PSN.
  // See the Authenticating Manually docs for how to get your NPSSO.
  const npsso = "xxxxxxxx";
  const accessCode = await exchangeNpssoForCode(npsso);
  const authorization = await exchangeCodeForAccessToken(accessCode);

  // 2. Get the user's `accountId` from the username.
  const allAccountsSearchResults = await makeUniversalSearch(
    authorization,
    "xelnia",
    "SocialAllAccounts"
  );

  const targetAccountId =
    allAccountsSearchResults.domainResponses[0].results[0].socialMetadata
      .accountId;

  // 3. Get the user's list of titles (games).
  const { trophyTitles } = await getUserTitles(authorization, targetAccountId);

  const games: any[] = [];
  for (const title of trophyTitles) {
    // 4. Get the list of trophies for each of the user's titles.
    const { trophies: titleTrophies } = await getTitleTrophies(
      authorization,
      title.npCommunicationId,
      "all",
      {
        npServiceName:
          title.trophyTitlePlatform !== "PS5" ? "trophy" : undefined
      }
    );

    // 5. Get the list of _earned_ trophies for each of the user's titles.
    const { trophies: earnedTrophies } = await getUserTrophiesEarnedForTitle(
      authorization,
      targetAccountId,
      title.npCommunicationId,
      "all",
      {
        npServiceName:
          title.trophyTitlePlatform !== "PS5" ? "trophy" : undefined
      }
    );

    // 6. Merge the two trophy lists.
    const mergedTrophies = mergeTrophyLists(titleTrophies, earnedTrophies);

    games.push({
      gameName: title.trophyTitleName,
      platform: title.trophyTitlePlatform,
      trophyTypeCounts: title.definedTrophies,
      earnedCounts: title.earnedTrophies,
      trophyList: mergedTrophies
    });
  }

  // 7. Write to a JSON file.
  fs.writeFileSync("./games.json", JSON.stringify(games));
}

const mergeTrophyLists = (
  titleTrophies: Trophy[],
  earnedTrophies: Trophy[]
) => {
  const mergedTrophies: any[] = [];

  for (const earnedTrophy of earnedTrophies) {
    const foundTitleTrophy = titleTrophies.find(
      (t) => t.trophyId === earnedTrophy.trophyId
    );

    mergedTrophies.push(
      normalizeTrophy({ ...earnedTrophy, ...foundTitleTrophy })
    );
  }

  return mergedTrophies;
};

const normalizeTrophy = (trophy: Trophy) => {
  return {
    isEarned: trophy.earned ?? false,
    earnedOn: trophy.earned ? trophy.earnedDateTime : "unearned",
    type: trophy.trophyType,
    rarity: rarityMap[trophy.trophyRare ?? 0],
    earnedRate: Number(trophy.trophyEarnedRate),
    trophyName: trophy.trophyName,
    groupId: trophy.trophyGroupId
  };
};

const rarityMap: Record<TrophyRarity, string> = {
  [TrophyRarity.VeryRare]: "Very Rare",
  [TrophyRarity.UltraRare]: "Ultra Rare",
  [TrophyRarity.Rare]: "Rare",
  [TrophyRarity.Common]: "Common"
};

我一直在寻找可能的修复方法,例如将“type”:“module”添加到 package.json,尝试在我的 js 文件中导入或以其他方式定义 psn-api,但我不断出错。 我确信我有一些基本的误解。 如果有人可以概述我需要采取的直接步骤以使示例脚本在 cmd 行中运行,我将非常感激。

我的 package.json 就这样:

    {
  "name": "psnapitest",
  "version": "1.0.0",
  "description": "",
  "main": "index3.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@types/node": "^18.6.2",
    "psn-api": "^2.7.0"
  },
  "type": "module",
  "devDependencies": {
    "@tsconfig/node16": "^1.0.3",
    "typescript": "^4.7.4"
  }
}

我的 tsconfig.json 就这样(在评论中提出建议):

{
  "compilerOptions": {
    "target": "es2016",
    "module": "es6",
    "moduleResolution": "node",
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true
  }
}

运行编译后的 js 时的当前错误:

现在编译没有问题。

我运行node index.js并得到以下错误

    exports.__esModule = true;
^

ReferenceError: exports is not defined in ES module scope

尝试而不是使用导入,使用要求:

const fs = require('fs')
const psn = require('psn-api')
type { Trophy } = psn
const { exchangeCodeForAccessToken } = psn
const { exchangeNpssoForCode } = psn
const { getTitleTrophies } = psn
const { getUserTitles } = psn
const { getUserTrophiesEarnedForTitle } = psn
const { makeUniversalSearch } = psn
const { TrophyRarity } = psn

此外,不要将其编译为 node.js,而是尝试使用此库: https://www.npmjs.com/package/ts-node

它基本上是 node.js 但对于 typescript

我在本地尝试过,没有错误

使用节点库时,您需要在tsconfig.json上设置"moduleResolution": "node"

索引.ts

import fs from 'fs'

package.json

{
  "name": "psn-api-test",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "tsc index.ts",
    "start": "node index.js"
  },
  "type": "module",
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "psn-api": "^2.7.0"
  },
  "devDependencies": {
    "@types/node": "^18.6.2",
    "typescript": "^4.7.4"
  }
}

tsconfig.json

{
  "compilerOptions": {
    "target": "es2016",
    "module": "es6",
    "moduleResolution": "node",
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM