I'm writing a script to be executed with truffle exec and I need to add some logic conditional on the network we're calling truffle exec with.

This is (roughly) what I want in my script:

const contract = artifacts.require("./MyContract.sol");
module.exports = function(callback) {
  // TODO: Do some conditional thing based on network!


I'm hoping to call this script in the following way:

truffle exec script.js --network ropsten

Not sure if this is the best method, but the arguments you pass to truffle, including the network, are available under process.argv.


process.argv.forEach(function (val, index, array) {
  console.log(index + ': ' + val);


> truffle exec script.js --network development
Using network 'development'.

0: /usr/bin/node
1: /usr/bin/truffle
2: exec
3: foo.js
4: --network
5: development

So access that array at the relevant index for the network name.

  • In which case, the --network argument is redundant. Unlike truffle migrate and truffle deploy (which are identical btw), truffle exec and truffle test do not receive the network as an argument, so one has to pass it explicitly and then access it via process.argv. – goodvibration May 14 '19 at 6:56
  • Ah, good point - which must be why it's outputting the line Using network 'development', i.e. "I don't know which network to use, so using the first one in the config file." – Richard Horrocks May 14 '19 at 7:05
  • Actually, now that you've mentioned it... It kinda makes me think that perhaps truffle test can somehow be configured with a specific network. I guess it'll require looking into their source code... – goodvibration May 14 '19 at 7:11
  • Not the cleanest, but this works! Thanks for the suggestion. – lsankar4033 May 14 '19 at 17:45

You can use web3.eth.network api .

'use strict';

global.artifacts = artifacts;
global.web3 = web3;

async function main(){
    const newtworkType = await web3.eth.net.getNetworkType();
    const networkId = await web3.eth.net.getId();
    console.log("network type:"+newtworkType);
    console.log("network id:"+networkId);

// For truffle exec
module.exports = function(callback) {
    main().then(() => callback()).catch(err => callback(err))

I hope it can be useful :)


You can define your network in truffle-config.js

For example:

const HDWalletProvider = require('truffle-hdwallet-provider');

module.exports = {
  test: {
    host: ``,
    port: 9999,
    network_id: 3,
    gas: 5500000,
    confirmations: 2,
    timeoutBlocks: 200,
    skipDryRun: true
  ropsten: {
    provider: () => new HDWalletProvider(mnemonicOrPrivatekey, `https://rinkeby.infura.io/${infuraKey}`),
    network_id: 3,
    gas: 5500000,
    confirmations: 2,
    timeoutBlocks: 200,
    skipDryRun: true

Then you can run script with --network test

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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