Ошибка, связаная с require("chalk")
let hash = require('object-hash');
const TARGET_HASH = 20;
let validator = require("./validator");
let mongoose = require("mongoose");
let blockChainModel = mongoose.model("BlockChain");
let chalk = require("chalk");
// import chalk from 'chalk';
class BlockChain{
constructor(){
this.chain = [];
this.curr_transactions = [];
}
addNewBlock(prevHash){
let block = {
index: this.chain.length + 1,
timestamp: Date.now(),
transactions: this.curr_transactions,
prevHash: prevHash,
};
if(validator.proofOfWork() == TARGET_HASH){
block.hash = hash(block);
let newBlock = new blockChainModel(this.block);
newBlock.save((err) => {
if(err) return console.log(chalk.red("Blok not added to db", err.message));
console.log(chalk.green("block added to db"));
});
this.chain.push(block);
this.curr_transactions = [];
return block;
}
}
addNewTransaction(sender, recipient, amount){
this.curr_transactions.push({sender, recipient, amount});
}
lastBlock(){
return this.chain.slice(-1)[0];
}
isEmpty(){
return this.chain.length == 0;
}
}
module.exports = BlockChain;
Ошибка: let chalk = require("chalk"); ^
Error [ERR_REQUIRE_ESM]: require() of ES Module C:\Users\...\blockchain_bazadanych\node_modules\chalk\source\index.js from C:\Users\...\blockchain_bazadanych\blockChain.js not supported.
Instead change the require of index.js in C:\Users\losas\OneDrive\Рабочий стол\blockchain_bazadanych\blockChain.js to a dynamic import() which is available in all CommonJS modules.
Попробовал заменить
let chalk = require("chalk"); на import chalk from 'chalk'; и добавил "type": "module", в package.json(
{
"dependencies": {
"type": "module",
"chalk": "^5.2.0",
"mongodb": "^5.0.1",
"mongoose": "^6.9.1",
"node-fetch": "^2.6.1",
"object-hash": "^3.0.0"
}
}, не помогло
Источник: Stack Overflow на русском