我正在使用 node js 來編譯智能合約。
我想從這個智能合約中匯入兩個物件(代表兩個合約)并將它們存盤在一個名為“build”的檔案目錄中,并帶有 JSON 擴展名。
當我運行命令 node compile.js 時,出現此錯誤:
errno: -4058, syscall: 'open', code: 'ENOENT'.
當我除錯我的代碼時,錯誤是從 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]
);
}

uj5u.com熱心網友回復:
此錯誤表明該檔案不存在。讀取檔案時會出現錯誤,請確保在讀取檔案之前存在該檔案,因為 fs.outputJsonSync如果檔案不存在,則會創建該檔案。
// 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");
});
嘗試將readFileSync方法保留在 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}`);
}
}
最好將不同的操作包裹在不同的 try/catch 下進行錯誤分離。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/376523.html
