I have a local blockchain running on http://127.0.0.1:7545 using Ganache. There are 8 blocks on the blockchain, none of them is pending.
I've made a script in nodejs that uses web3 to get data from the blocks, but for some reason it isn't working.
This is the script:
Web3 = require('Web3')
const web3 = new Web3('http://127.0.0.1:7545')
console.log(web3.eth.getBlockNumber())
var block = web3.eth.getBlock('latest')
console.log(block)
var firstblock = web3.eth.getBlock(0)
console.log(firstblock)
console.log(firstblock.hash)
and this is the script execution output
>node script.js
Promise { <pending> }
Promise { <pending> }
Promise { <pending> }
undefined
The getBlock
method always returns a promise. You should add a .then()
if you want to access to the block object.
So it should be something like this:
Web3 = require('Web3')
const web3 = new Web3('http://127.0.0.1:7545')
web3.eth.getBlockNumber().then(console.log)
var block = web3.eth.getBlock('latest')
block.then(console.log)
var firstblock = web3.eth.getBlock(0)
firstblock.then(console.log)
firstblock.then( block => console.log(block.hash))