[英]How to print the current block in the blockchain using node.js?
I have a simple Blockchain to generate block.我有一个简单的区块链来生成块。 I want to print the current block only.我只想打印当前块。
My code:我的代码:
class Block {
constructor(index, data) {
this.index = index;
this.timestamp = Date.now();
this.data = data;
this.id = uuidv4();
}
static genesis(){
return new this(0, 'data gensis');
}
}
class BlockChain {
constructor() {
this.chain = [Block.genesis()];
}
addBlock(data) {
let index = this.chain.length;
let block = new Block(index, data);
this.chain.push(block);
}
}
The print the chain:打印链条:
let BChain = new BlockChain();
BChain.addBlock(jsMsgData.msg)
console.log(JSON.stringify(BChain, null, 4));
The output: output:
{
"chain": [
{
"index": 0,
"timestamp": 1615484160580,
"data": "data gensis",
"id": "5326f3e4-67d9-48b7-b2db-9b8daf16b405"
},
{
"index": 1,
"timestamp": 1615484160581,
"data": [
{
"parent": "1",
"child": "2"
},
{
"parent": "3",
"child": "4"
}
],
"id": "71ac1cf4-621b-4631-b81e-cfeaca7ca5f5"
}
]
}
I receive data like this:我收到这样的数据:
client.on('message', function (topic, message) {
const jsArray = JSON.parse(message);
jsArray.forEach(jsMsgData => {
BChain.addBlock(jsMsgData.msg)
});
}
I want to print the current block (for example index 1).我想打印当前块(例如索引 1)。
How could do that, please?请问怎么可以这样?
Thanks in advance.提前致谢。
To get the current block (which is basically the last block on the chain) you can add a getCurrentBlock
method on your Blockchain class like this要获取当前块(基本上是链上的最后一个块),您可以像这样在区块链 class 上添加getCurrentBlock
方法
class BlockChain {
constructor() {
this.chain = [Block.genesis()];
}
addBlock(data) {
let index = this.chain.length;
let block = new Block(index, data);
this.chain.push(block);
}
getCurrentBlock() {
return this.chain[this.chain.length - 1];
}
}
let BChain = new BlockChain();
BChain.addBlock(jsMsgData.msg)
BChain.getCurrentBlock() // should return the current block here
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.