Search code examples
javascriptreactjsnode.jsweb3js

Running web3 in NodeJs enviroment


When I attempt to import web3 in NodeJS enviroment while on the project directory I get undefined error.

> const { Web3 } = require('web3');
undefined
> const web3 = new Web3('https://eth-sepolia.g.alchemy.com/v2/9aHCL7I90Xo_YSRD3P1PxkyMEANMyWl7')
undefined

Any ideas?


Solution

  • There is a website that explains the simple and basic web3 topic and in addition, there is a video in it that explained everything in brief. That I found Learn-web3-nodejs or you can use another one website Official documentation for web3.js

    I recommend visiting it. And it shows that you need to install web3 library in your project

    • npm install web3

    (of course in your node js) and then import to the file you are working with

    const Web3 = require('web3');
    const web3 = new Web3('https://eth-sepolia.g.alchemy.com/v2/9aHCL7I90Xo_YSRD3P1PxkyMEANMyWl7');
    " And of course there are some functions you can run that I found in the documentation example code: web3 "// Import web3
    const Web3 = require('web3');
    
    // Create a new instance of web3 with the provided URL
    const web3 = new Web3('https://eth-sepolia.g.alchemy.com/v2/9aHCL7I90Xo_YSRD3P1PxkyMEANMyWl7');
    
    // Check if web3 is connected to the network
    web3.eth.net.isListening()
     .then(() => console.log('Connected to the network'))
     .catch(e => console.log('Something went wrong', e));
    

    with a command as explained

    • node yourFileName.js

    (you can change the name if you want), good luck