web3.js can communicate with nodes using HTTP or IPC. We will use HTTP to set up communication with nodes. web3.js allows us to establish connections with multiple nodes. An instance of web3 represents a connection with a node. The instance exposes the APIs.
When an app is running inside Mist, it automatically makes an instance of web3 available that's connected to the mist node. The variable name of the instance is web3.
Here is the basic code to connect to a node:
if (typeof web3 !== 'undefined') {
web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
}
At first, we check here whether the code is running inside mist by checking whether web3 is undefined or not. If web3 is defined, then we use the already available instance; otherwise, we create an instance by connecting to our custom node. If you want to connect to the custom node regardless of whether the app is running inside mist or not, then remove the if condition form the preceding code. Here, we are assuming that our custom node is running locally on port number 8545.
The Web3.providers object exposes constructors (called providers in this context) to establish a connection and transfer messages using various protocols. Web3.providers.HttpProvider lets us establish an HTTP connection, whereas Web3.providers.IpcProvider lets us establish an IPC connection.
The web3.currentProvider property is automatically assigned to the current provider instance. After creating a web3 instance, you can change its provider using the web3.setProvider() method. It takes one argument, that is, the instance of the new provider.
web3 exposes a isConnected() method, which can be used to check whether it's connected to the node or not. It returns true or false depending on the connection status.