TypeError: Cannot read property 'split' of undefined


I am trying to compile the following code:

var assert = require('assert');
     const path = require("path");
     const fs = require("fs");
//const  F5 = artifacts.require("F5")
//const ST5= artifacts.require("ST5")

module.exports = async function(callback) {
try {
     var ctr =0;
     const keyWordStr = [];
     const files = new Array("A1.sol", "A2.sol", "A3.sol");
     const keyWords = new Array("string1",  "string2", "string3","string4", "string5", "string6", "string7");
     const str = 0;
     for (let i = 0; i < files.length; i++) {   
        const contractPath = path.resolve('/home/zulfi/Truffle_programs/search_opcode/','contracts',files[i]);
        const contractCode2 = fs.readFileSync(contractPath, "utf8");
        var lines = this.contractCode2.split(/\r\n|\n/);
        for(var line = 0; line < lines.length-1; line++){
           keyWordStr[ctr] = (lines[line].search(keyWords[ctr] >= 0) ? lines[line] : false);
           console.log(line + " --> "+ lines[line]);
        }//for (var...)   
  catch(error) {


I am getting the following error:

$ truffle exec tool2.js
Using network 'development'.

TypeError: Cannot read property 'split' of undefined
    at module.exports (/home/zulfi/Truffle_programs/search_opcode/tool2.js:19:40)
    at Object.exec (/home/zulfi/.nvm/versions/node/v10.23.3/lib/node_modules/truffle/build/webpack:/packages/require/require.js:127:1)
    at Promise (internal/util.js:274:30)
    at new Promise (<anonymous>)
    at bound exec (internal/util.js:273:12)
    at Object.run (/home/zulfi/.nvm/versions/node/v10.23.3/lib/node_modules/truffle/build/webpack:/packages/core/lib/commands/exec.js:80:1)
    at process._tickCallback (internal/process/next_tick.js:68:7)

Somebody please guide me.



Hi, Zulfi

The problem is here, you’re trying to access property of current object, but contractCode2 is not a property but a simple const variable. Just remove this. to fix it:

let lines = contractCode2.split(/\r\n|\n/); //fixed

If you want contractCode2 to be a property for some reason, you should set it like so:

this.contractCode2 = fs.readFileSync(contractPath, "utf8");

but looking at your code I don’t think this is necessarily.

Also, it is recommended to use let keyword for local variables instead of var. Learn more why.


This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.