0

I'm trying to test basic web3 with node. I have testrpc running and I have the following in a javascript file:

var Web3 = require('web3');

var web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));

console.log(web3.eth.accounts[0]);

When I run node filename.js it returns undefined. Why is that?

When I change web3.eth.accounts[0] to web3.eth.accounts I get this :

Accounts {
currentProvider: [Getter/Setter],
_requestManager:
 RequestManager {
 provider: HttpProvider { host: 'http://localhost:8545', timeout: 0, connected: false },
 providers:
  { WebsocketProvider: [Function: WebsocketProvider],
    HttpProvider: [Function: HttpProvider],
    IpcProvider: [Function: IpcProvider] },
 subscriptions: {} },
givenProvider: null,
providers:
{ WebsocketProvider: [Function: WebsocketProvider],
 HttpProvider: [Function: HttpProvider],
 IpcProvider: [Function: IpcProvider] },
_provider: HttpProvider { host: 'http://localhost:8545', timeout: 0, connected: false },
setProvider: [Function],
_ethereumCall:
{ getId:
  { [Function: send]
    method: [Object],
    request: [Function: bound ],
    call: 'net_version' },
 getGasPrice:
  { [Function: send]
    method: [Object],
    request: [Function: bound ],
    call: 'eth_gasPrice' },
 getTransactionCount:
  { [Function: send]
    method: [Object],
    request: [Function: bound ],
    call: 'eth_getTransactionCount' } },
wallet:
Wallet {
 _accounts: [Circular],
 length: 0,
 defaultKeyName: 'web3js_wallet' } }

1 Answer 1

1

Does the async call work?

web3.eth.getAccounts((error, result) => {
  if (result && result.length > 0) {
    console.log(result[0]);
  }
  else {
    console.error("Error: ", error);
  }
}

Also be sure to double check that you didn't start testrpc on another port and that it's up and listening (I've had the process die on me more than once without noticing).

3
  • I actually just ran your code snippet and it worked. Do you know why I can't run it regularly? Commented Nov 10, 2017 at 0:57
  • 1
    @JorahFriendzone Are you using web3 v1.0 beta? That version only supports async calls, ie callbacks or promievents.
    – Ismael
    Commented Nov 10, 2017 at 3:45
  • @Ismael Yeah that was the problem, I was on v1.0 beta. Thanks! Commented Nov 10, 2017 at 19:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.