I have run into something that seems pretty weird to me, although there's a good chance it's just a basic knowledge gap issue. As you can see, the following execution within the Node console produces the desired result, i.e. outputting the number of account addresses stored in accounts
:
> var Web3 = require("web3");
undefined
> var web3 = new Web3(new
Web3.providers.HttpProvider("http://localhost:8545"));
undefined
> var accounts;
undefined
> web3.eth.getAccounts().then(_accounts => { accounts = _accounts });
Promise {
_bitField: 0,
_fulfillmentHandler0: undefined,
_rejectionHandler0: undefined,
_promise0: undefined,
_receiver0: undefined }
> console.log(accounts.length);
10
undefined
However, running an external js file containing the exact same code
var Web3 = require("web3");
var web3 = new Web3(new
Web3.providers.HttpProvider("http://localhost:8545"));
var accounts;
web3.eth.getAccounts().then(_accounts => { accounts = _accounts });
console.log(accounts.length);
produces the following error:
➜ ethtest node test.js
/home/brandon/ethtest/test.js:8
console.log(accounts.length);
^
TypeError: Cannot read property 'length' of undefined
at Object.<anonymous> (/home/brandon/ethtest/test.js:8:21)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.runMain (module.js:604:10)
at run (bootstrap_node.js:383:7)
at startup (bootstrap_node.js:149:9)
at bootstrap_node.js:496:3
What could be the difference? Am I simply attempting something that cannot be done? Any help will be much appreciated, and thanks in advance!