Home > OS >  How can i fix the error coming from fs.outputJsonSync node.js
How can i fix the error coming from fs.outputJsonSync node.js

Time:12-06

I'm using node js to compile a smart contract.

I want to import from this smart contract two objects(represents two contracts) and store them in a file directory called "build" with a JSON extension.

When I run the command node compile.js, I got this error:

errno: -4058, syscall: 'open', code: 'ENOENT'.

When I've debugged my code, the error occurred from fs.outputJsonSync?

const path = require("path");
const fs = require("fs-extra");

const solc = require("solc");

const buildPath = path.resolve(__dirname, "build");

fs.removeSync(buildPath);


const campaignPath = path.resolve(__dirname, "contracts", "Campaign.sol");


const source = fs.readFileSync(campaignPath, "utf8");


const output = solc.compile(source, 1).contracts;
console.log(output);

fs.ensureDirSync(buildPath);

// To loop throught the contracts that contains 2 objects with data 
for (let contract in output) { 
    fs.outputJsonSync(
        path.resolve(buildPath, contract   ".json"),
        output[contract] 
    );
}

enter image description here

CodePudding user response:

This error states that the file doesn't exist. The error comes in when you are reading the file, make sure the file exist before you read it because fs.outputJsonSync creates the file if it doesn't exist.

// Function call
// Using callback function
fs.outputJSON(file, {name: "David"}, err => {
  if(err) return console.log(err);
  console.log("Object written to given JSON file");
});

Try to keep the readFileSync method in try/catch:

const path = require("path");
const fs = require("fs-extra");

const solc = require("solc");

const buildPath = path.resolve(__dirname, "build");

fs.removeSync(buildPath);

let output;
const campaignPath = path.resolve(__dirname, "contracts", "Campaign.sol");

try {
const source = fs.readFileSync(campaignPath, "utf8");
      output = solc.compile(source, 1).contracts;
console.log(output);
fs.ensureDirSync(buildPath);
} catch (e) {
  console.log(`Error while reading the file ${e}`);
}


// To loop throught the contracts that contains 2 objects with data 
for (let contract in output) { 
   try {
    fs.outputJsonSync(
        path.resolve(buildPath, contract   ".json"),
        output[contract] 
    );
   } catch (e) {
      console.log(`Error while writing JSON: ${e}`);
   }
}

It is good to wrap different operations under different try/catch for error separation.

  • Related