【问题标题】:TypeError [ERR_INVALID_ARG_TYPE]: 第一个参数必须是字符串类型或Buffer、ArrayBuffer 或Array 的实例... | Web3.js 错误
【发布时间】:2026-01-17 10:20:06
【问题描述】:

一旦我尝试跑步:

node app.js

我收到以下错误消息:

buffer.js:330
  throw new ERR_INVALID_ARG_TYPE(
  ^

TypeError [ERR_INVALID_ARG_TYPE]: The first argument must be of type string or an instance of Buffer, ArrayBuffer, or Array or an Array-like Object. Received undefined
    at Function.from (buffer.js:330:9)
    at Object.<anonymous> (C:\DappUniversity-web3js\app.js:8:28)
    at Module._compile (internal/modules/cjs/loader.js:1072:14)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1101:10)
    at Module.load (internal/modules/cjs/loader.js:937:32)
    at Function.Module._load (internal/modules/cjs/loader.js:778:12)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:76:12)
    at internal/main/run_main_module.js:17:47 {
  code: 'ERR_INVALID_ARG_TYPE'
}

这是我在 app.js 文件中写的内容:

app.js

var Tx = require('ethereumjs-tx')
const Web3 = require('web3')
const web3 = new Web3('https://ropsten.infura.io/v3/0aa71df89e464ba9b0a3b35449346dac')

const account1 = '0x31C662426bA57409b3F53ececAbcfA7c6EA43163'
const account2 = '0xa00739C3A4B34C4D2Cb66386d8377EE951521e86'

const privatekey1 = Buffer.from(process.env.PRIVATE_KEY_1)
const privatekey2 = Buffer.from(process.env.PRIVATE_KEY_2)

web3.eth.getBalance(account1, (err, bal) => {
    console.log('account 1 balance:', web3.utils.fromWei(bal,'ether'))
})

web3.eth.getBalance(account2, (err, bal) => {
    console.log('account 2 balance:', web3.utils.fromWei(bal,'ether'))
})

我只是想获取两个帐户地址的余额,但一直收到错误消息。虽然我确实尝试过卸载 npm 包 web3 和 ethereumjs-tx,但仍然没有解决这个问题。

那么,应该如何纠正这个错误呢?我在这里做错了什么还是因为缺少一些 npm 包文件或详细信息?

任何帮助将不胜感激!

【问题讨论】:

    标签: ethereum private-key web3 web3js metamask


    【解决方案1】:

    错误与以下任一行有关:

    const privatekey1 = Buffer.from(process.env.PRIVATE_KEY_1)
    const privatekey2 = Buffer.from(process.env.PRIVATE_KEY_2)
    

    您正在尝试从无效(很可能是undefined)值创建缓冲区。

    process.env.&lt;variable_name&gt; 默认情况下仅从环境变量加载(例如,由您的系统、Docker 容器或命令行参数传递)。

    例子:

    # sets the `process.env.PRIVATE_KEY_1` value in the node script
    PRIVATE_KEY_1=123456 node index.js
    

    它不会自动加载.env 文件内容。为此,您可以使用dotenv 包。

    【讨论】:

      最近更新 更多