一旦我尝试运行:
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-web3jsapp.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包文件或详细信息?
错误与以下任一行有关:
const privatekey1 = Buffer.from(process.env.PRIVATE_KEY_1)
const privatekey2 = Buffer.from(process.env.PRIVATE_KEY_2)
您正试图从无效(很可能是undefined
(值创建缓冲区。
默认情况下,process.env.<variable_name>
仅从环境变量加载(例如,由系统、Docker容器或命令行参数传递(。
示例:
# sets the `process.env.PRIVATE_KEY_1` value in the node script
PRIVATE_KEY_1=123456 node index.js
它不会自动加载.env
文件内容。为此,您可以使用dotenv软件包。