簡體   English   中英

(hashlips_art_engine-1.1.2_patch_v5) “路徑”參數必須是字符串類型。 收到未定義

[英](hashlips_art_engine-1.1.2_patch_v5) The "path" argument must be of type string. Received undefined

我正在嘗試更新 10 個 JSON 文件的一些元數據,其中一些得到正確更新,而另一些則給我以下錯誤。

您可以在下面看到 6 個文件給我錯誤,並且 4 個文件已正確更新。


錯誤:TypeError [ERR_INVALID_ARG_TYPE]:“路徑”參數必須是字符串類型。 收到未定義

錯誤:TypeError [ERR_INVALID_ARG_TYPE]:“路徑”參數必須是字符串類型。 收到未定義

錯誤:TypeError [ERR_INVALID_ARG_TYPE]:“路徑”參數必須是字符串類型。 收到未定義

錯誤:TypeError [ERR_INVALID_ARG_TYPE]:“路徑”參數必須是字符串類型。 收到未定義

錯誤:TypeError [ERR_INVALID_ARG_TYPE]:“路徑”參數必須是字符串類型。 收到未定義

錯誤:TypeError [ERR_INVALID_ARG_TYPE]:“路徑”參數必須是字符串類型。 收到未定義

5.png 上傳 & 5.json 更新!

4.png 上傳 & 4.json 更新!

1.png 上傳 & 1.json 更新!

7.png 上傳 & 7.json 更新!


這是我使用的 node.js 代碼:

onst FormData = require('form-data');
const fetch = require('node-fetch');
const path = require("path");
const basePath = process.cwd();
const fs = require("fs");

fs.readdirSync(`${basePath}/build/images`).
forEach(file => {
  const formData = new FormData();
  const fileStream = fs.createReadStream(`${basePath}/build/images/${file}`);
  formData.append("file", fileStream);

  let url = 'https://api.nftport.xyz/v0/files';

  let options = {
    method: 'POST',
    headers: {
      Authorization: 'SecretApiCode',
    },
    body: formData
  };

  fetch(url, options)
    .then(res => res.json())
    .then((json) => {
      const fileName = path.parse(json.file_name).name;
      let rawdata = fs.readFileSync(`${basePath}/build/json/${fileName}.json`);
      let metaData = JSON.parse(rawdata);

      metaData.file_url = json.ipfs_url;

      fs.writeFileSync(`${basePath}/build/json/${fileName}.json`,
        JSON.stringify(metaData, null, 2));

      console.log(`${json.file_name} uploaded & ${fileName}.json updated!`);
      })
    .catch(err => console.error('error:' + err));

});

我有 10png 文件:

1.png 2.png 3.png 4.png 5.png 6.png 7.png 8.png 9.png 10.png

和10個JSON文件

1.json 2.json 3.json 4.json 5.json 6.json 7.json 8.json 9.json 10.json

您的代碼中的問題似乎與獲取 URL 有關。

事實證明,有時,您的代碼會因錯誤而失敗,有時,它會成功運行。

可能發生的情況是,有時,當您從 URL 獲取數據時,它可能沒有file_name屬性(由於錯誤等)

當您嘗試使用以下方法解析路徑時:

path.parse(json.file_name);

file_name可能undefined ,因為可能沒有這樣的鍵。 而且,由於path.parse()無法解析undefined ,它會返回一個錯誤,表示 in 只接受string s(如下所示)。

TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received undefined

有許多可能的解決方案,因此在下面列出。

  • 添加檢查file_name是否可用。 如果不是,則不要嘗試使用path.parse()解析它。 您可以使用下面的代碼來檢查它(在第二個.then()方法中)。

     if (.json.file_name) { console.error("Error fetching file name;"); return; }
  • 如果您的 API 支持,請檢查響應正文中是否有錯誤。 假設錯誤類似於.error ,您可以使用下面的代碼作為指導(將其添加到第二個.then()方法中)。

     if (.json.file_name && json.error) { console.log(json.error;message); return; }
  • 可能還有許多其他(更好的)解決方案,但這些解決方案只是為您提供一個起點。

解決方案 1 和 2 非常相似,但它們在不同的情況下工作。

// 嘗試這個。 如果您將標簽更改為 v1.2.0,您還可以在 codeSTACKr/create-10k-nft-collection" git 存儲庫中找到它。

//這是在uploadfiles.js

const FormData = require("form-data");
const fetch = require("node-fetch");
const path = require("path");
const basePath = process.cwd();
const fs = require("fs");

const AUTH = 'Your API KEY GOES HERE';
const TIMEOUT = 1000; // Milliseconds. Extend this if needed to wait for each upload. 1000 = 1 second.

const allMetadata = [];

async function main() {
  const files = fs.readdirSync(`${basePath}/build/images`);
  files.sort(function(a, b){
    return a.split(".")[0] - b.split(".")[0];
  });
  for (const file of files) {
    const fileName = path.parse(file).name;
    let jsonFile = fs.readFileSync(`${basePath}/build/json/${fileName}.json`);
    let metaData = JSON.parse(jsonFile);
    if(!metaData.file_url.includes('https://')) {
      const response = await fetchWithRetry(file);
      metaData.file_url = response.ipfs_url;
  
      fs.writeFileSync(
        `${basePath}/build/json/${fileName}.json`,
        JSON.stringify(metaData, null, 2)
      );
      console.log(`${response.file_name} uploaded & ${fileName}.json updated!`);
    } else {
      console.log(`${fileName} already uploaded.`);
    }

    allMetadata.push(metaData);
  }
  fs.writeFileSync(
    `${basePath}/build/json/_metadata.json`,
    JSON.stringify(allMetadata, null, 2)
  );
}

main();

function timer(ms) {
  return new Promise(res => setTimeout(res, ms));
}

async function fetchWithRetry(file)  {
  await timer(TIMEOUT)
  return new Promise((resolve, reject) => {
    const fetch_retry = (_file) => {
      const formData = new FormData();
      const fileStream = fs.createReadStream(`${basePath}/build/images/${_file}`);
      formData.append("file", fileStream);

      let url = "https://api.nftport.xyz/v0/files";
      let options = {
        method: "POST",
        headers: {
          Authorization: AUTH,
        },
        body: formData,
      };

      return fetch(url, options).then(async (res) => {
          const status = res.status;

          if(status === 200) {
            return res.json();
          }            
          else {
            console.error(`ERROR STATUS: ${status}`)
            console.log('Retrying')
            await timer(TIMEOUT)
            fetch_retry(_file)
          }            
      })
      .then(async (json) => {
        if(json.response === "OK"){
          return resolve(json);
        } else {
          console.error(`NOK: ${json.error}`)
          console.log('Retrying')
          await timer(TIMEOUT)
          fetch_retry(_file)
        }
      })
      .catch(async (error) => {  
        console.error(`CATCH ERROR: ${error}`)  
        console.log('Retrying')    
        await timer(TIMEOUT)    
        fetch_retry(_file)
      });
    }        
    return fetch_retry(file);
  });
}

暫無
暫無

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

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