Search code examples
javascriptweb3jstruffle

How can I execute a script with environment variable and execute with truffle


I created a script to build hash so I usually executed that like this:

$ truffle develop
truffle(develop)> exec scripts/myScript.js

but my script now want to read from .env

SIGNER= "56443876ca1ea534cc8ddc422f8ab891690325d173916c528d76483681b97fd6"

this is my script

require('dotenv').config();
const fs = require("fs");
const readline = require("readline");
const Web3 = require("web3");
const web3 = new Web3(Web3.givenProvider || "http://127.0.0.1:7545");
console.log('AAA', process.env.SIGNER);

I am getting

AAA undefined


Solution

  • try this :

    $ truffle init test-contract
    $ cd test-contract
    $ npm init -y
    $ npm i web3 --save
    $ npm i dotenv --save
    

    create a file inside your test folder and write it (test-contract/test/1.test.js) : 1.test.js

    require("dotenv").config();
    
    const Web3 = require("web3");
    const web3 = new Web3(Web3.givenProvider || "http://127.0.0.1:7545");
    console.log("AAA", process.env.SIGNER);
    

    then create .env file (test-contract/.env) and put following without space :

    SIGNER="56443876ca1ea534cc8ddc422f8ab891690325d173916c528d76483681b97fd6"
    

    finally run the (inside the test-contract folder)

    $ truffle test
    

    result :

    Compiling your contracts...
    ===========================
    > Compiling ./contracts/Migrations.sol
    > Artifacts written to /tmp/test--11623-Aa2e6hYzLkeX
    > Compiled successfully using:
       - solc: 0.8.10+commit.fc410830.Emscripten.clang
    
    AAA 56443876ca1ea534cc8ddc422f8ab891690325d173916c528d76483681b97fd6
    
    
      0 passing (1ms)