- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
所以我在 nodejs 中构建了一个区块链,当我运行应用程序时,我的构造函数变量传递未定义,尽管我这样做是为了将变量作为索引文件中的对象传递。下面将显示以下相关文件...
用于发布订阅的 PubNub:
const PubNub = require('pubnub');
const credentials = {
publishKey: 'pub-c-274ab4f3-redacted',
subscribeKey: 'sub-c-fe7d959c-redacted',
secretKey: 'sec-c-cannotDisplay'
};
const CHANNELS = {
TEST: 'TEST',
BLOCKCHAIN: 'BLOCKCHAIN',
TRANSACTION: 'TRANSACTION'
};
class PubSub {
constructor({ blockchain, transactionPool, wallet }) {
this.blockchain = blockchain;
this.transactionPool = transactionPool;
this.wallet = wallet;
this.pubnub = new PubNub(credentials);
//where you put uuid
this.pubnub.subscribe({ channels: Object.values(CHANNELS) });
this.pubnub.addListener(this.listener());
}
broadcastChain() {
this.publish({
channel: CHANNELS.BLOCKCHAIN,
message: JSON.stringify(this.blockchain.chain)
});
}
broadcastTransaction(transaction) {
this.publish({
channel: CHANNELS.TRANSACTION,
message: JSON.stringify(transaction)
});
}
subscribeToChannels() {
this.pubnub.subscribe({
channels: [Object.values(CHANNELS)]
});
}
listener() {
return {
message: messageObject => {
const { channel, message } = messageObject;
console.log(`Message received. Channel: ${channel}. Message: ${message}`);
const parsedMessage = JSON.parse(message);
switch(channel) {
case CHANNELS.BLOCKCHAIN:
this.blockchain.replaceChain(parsedMessage, true, () => {
this.transactionPool.clearBlockchainTransactions(
{ chain: parsedMessage.chain }
);
});
break;
case CHANNELS.TRANSACTION:
if (!this.transactionPool.existingTransaction({
inputAddress: this.wallet.publicKey
})) {
this.transactionPool.setTransaction(parsedMessage);
}
break;
default:
return;
}
}
}
}
publish({ channel, message }) {
// there is an unsubscribe function in pubnub
// but it doesn't have a callback that fires after success
// therefore, redundant publishes to the same local subscriber will be accepted as noisy no-ops
this.pubnub.publish({ message, channel });//channel,message
}
broadcastChain() {
this.publish({
channel: CHANNELS.BLOCKCHAIN,
message: JSON.stringify(this.blockchain.chain)
});
}
broadcastTransaction(transaction) {
this.publish({
channel: CHANNELS.TRANSACTION,
message: JSON.stringify(transaction)
});
}
}
const testPubSub = new PubSub()
{
testPubSub.publish({channel: CHANNELS.TEST, message: 'testing'});
}
module.exports = PubSub;
const bodyParser = require('body-parser');
const express = require('express');
const request = require('request');
const path = require('path');
const Blockchain = require('./blockchain');
const PubSub = require('./app/pubsub');
const TransactionPool = require('./wallet/transaction-pool');
const Wallet = require('./wallet');
const TransactionMiner = require('./app/transaction-miner');
const PubSubNub = require('./app/pubsub.pubnub');
//127.0.0.1:6379
const isDevelopment = process.env.ENV === 'development';
//TRY PUBNUB (comment out)
/*const REDIS_URL = isDevelopment ?
'redis://127.0.0.1:6379' : //try 6379 19289
'redis://h:p602b6838e89da65c8c4d29a6a4f954452d1ece59c10b27a29ebf9808721cb8e2@ec2-35-153-115-238.compute-1.amazonaws.com:9819'//19289
*/
const DEFAULT_PORT = 3000;
const ROOT_NODE_ADDRESS =
`http://localhost:${DEFAULT_PORT}`;
const app = express();
const blockchain = new Blockchain();
const transactionPool = new TransactionPool();
const wallet = new Wallet();
//const pubsub = new PubSub({ blockchain, transactionPool, redisUrl: REDIS_URL });//redis
const pubsub = new PubSubNub({ blockchain, transactionPool, wallet }); // for PubNub //change back to PubSub if issues arise
const transactionMiner = new TransactionMiner({ blockchain, transactionPool, wallet, pubsub });
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, 'client/dist')));
//endpoint
app.get('/api/blocks', (req, res) => {
res.json(blockchain.chain);
});
app.get('/api/blocks/length', (req, res) => {
res.json(blockchain.chain.length);
});
app.get('/api/blocks/:id', (req, res) => {
const { id } = req.params;
const { length } = blockchain.chain;
const blocksReversed = blockchain.chain.slice().reverse();
let startIndex = (id-1) * 5;
let endIndex = id * 5;
startIndex = startIndex < length ? startIndex : length;
endIndex = endIndex < length ? endIndex : length;
res.json(blocksReversed.slice(startIndex, endIndex));
});
app.post('/api/mine', (req, res) => {
const { data } = req.body;
blockchain.addBlock({ data });
pubsub.broadcastChain();
res.redirect('/api/blocks');
});
app.post('/api/transact', (req, res) => {
const { amount, recipient } = req.body;
let transaction = transactionPool
.existingTransaction({ inputAddress: wallet.publicKey });
try {
if (transaction) {
transaction.update({ senderWallet: wallet, recipient, amount });
} else {
transaction = wallet.createTransaction({
recipient,
amount,
chain: blockchain.chain
});
}
} catch(error) {
return res.status(400).json({ type: 'error', message: error.message });
}
transactionPool.setTransaction(transaction);
pubsub.broadcastTransaction(transaction);
res.json({ type: 'success', transaction });
});
app.get('/api/transaction-pool-map', (req, res) => {
res.json(transactionPool.transactionMap);
});
app.get('/api/mine-transactions', (req, res) => {
transactionMiner.mineTransactions();
res.redirect('/api/blocks');
});
app.get('/api/wallet-info', (req, res) => {
const address = wallet.publicKey;
res.json({
address,
balance: Wallet.calculateBalance({ chain: blockchain.chain, address })
});
});
app.get('/api/known-addresses', (req, res) => {
const addressMap = {};
for (let block of blockchain.chain) {
for (let transaction of block.data) {
const recipient = Object.keys(transaction.outputMap);
recipient.forEach(recipient => addressMap[recipient] = recipient);
}
}
res.json(Object.keys(addressMap));
});
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'client/dist/index.html'));
});
const syncWithRootState = () => {
request({ url: `${ROOT_NODE_ADDRESS}/api/blocks` }, (error, response, body) => {
if (!error && response.statusCode === 200) {
const rootChain = JSON.parse(body);
console.log('replace chain on a sync with', rootChain);
blockchain.replaceChain(rootChain);
}
});
request({ url: `${ROOT_NODE_ADDRESS}/api/transaction-pool-map` }, (error, response, body) => {
if (!error && response.statusCode === 200) {
const rootTransactionPoolMap = JSON.parse(body);
console.log('replace transaction pool map on a sync with', rootTransactionPoolMap);
transactionPool.setMap(rootTransactionPoolMap);
}
});
};
if (isDevelopment) {
const walletFoo = new Wallet();
const walletBar = new Wallet();
const generateWalletTransaction = ({ wallet, recipient, amount }) => {
const transaction = wallet.createTransaction({
recipient, amount, chain: blockchain.chain
});
transactionPool.setTransaction(transaction);
};
const walletAction = () => generateWalletTransaction({
wallet, recipient: walletFoo.publicKey, amount: 5
});
const walletFooAction = () => generateWalletTransaction({
wallet: walletFoo, recipient: walletBar.publicKey, amount: 10
});
const walletBarAction = () => generateWalletTransaction({
wallet: walletBar, recipient: wallet.publicKey, amount: 15
});
for (let i=0; i<20; i++) {
if (i%3 === 0) {
walletAction();
walletFooAction();
} else if (i%3 === 1) {
walletAction();
walletBarAction();
} else {
walletFooAction();
walletBarAction();
}
transactionMiner.mineTransactions();
}
}
let PEER_PORT;
if (process.env.GENERATE_PEER_PORT === 'true') {
PEER_PORT = DEFAULT_PORT + Math.ceil(Math.random() * 1000);
}
const PORT = process.env.PORT || PEER_PORT || DEFAULT_PORT;
app.listen(PORT, () => {
console.log(`listening at localhost:${PORT}`);
if (PORT !== DEFAULT_PORT) {
syncWithRootState();
}
});
main@goldengates.club [~/public_html/Cypher-Network]# npm run start
> Cypher-Network@1.0.0 start /home/main/public_html/Cypher-Network
> npm run build-client & node index.js
> Cypher-Network@1.0.0 build-client /home/main/public_html/Cypher-Network
> npm run clean && parcel build client/src/index.html --out-dir client/dist
> Cypher-Network@1.0.0 clean /home/main/public_html/Cypher-Network
> rm -rf .cache client/dist
/home/main/public_html/Cypher-Network/app/pubsub.pubnub.js:16
constructor({ blockchain, transactionPool, wallet }) {
^
TypeError: Cannot destructure property 'blockchain' of 'undefined' as it is undefined.
at new PubSub (/home/main/public_html/Cypher-Network/app/pubsub.pubnub.js:16:17)
at Object.<anonymous> (/home/main/public_html/Cypher-Network/app/pubsub.pubnub.js:99:20)
at Module._compile (internal/modules/cjs/loader.js:1158:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1178:10)
at Module.load (internal/modules/cjs/loader.js:1002:32)
at Function.Module._load (internal/modules/cjs/loader.js:901:14)
at Module.require (internal/modules/cjs/loader.js:1044:19)
at require (internal/modules/cjs/helpers.js:77:18)
at Object.<anonymous> (/home/main/public_html/Cypher-Network/index.js:10:19)
at Module._compile (internal/modules/cjs/loader.js:1158:30)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! Cypher-Network@1.0.0 start: `npm run build-client & node index.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the Cypher-Network@1.0.0 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! /home/main/.npm/_logs/2020-03-27T18_49_30_710Z-debug.log
⠋ Building...lscpu: failed to determine number of CPUs: /sys/devices/system/cpu/possible: No such file or directory
✨ Built in 17.71s.
client/dist/src.a02dd135.js.map ⚠️ 1.17 MB 160ms
client/dist/src.a02dd135.js 501.63 KB 17.02s
client/dist/logo.04580eb6.png 50.84 KB 4.37s
client/dist/src.e852c4ed.css.map 957 B 4ms
client/dist/index.html 454 B 457ms
client/dist/src.e852c4ed.css 454 B 4.86s
最佳答案
这里:
class PubSub {
constructor({ blockchain, transactionPool, wallet }) {
const testPubSub = new PubSub()
PubSub
中的解构构造函数相当于
const { blockchain, transactionPool, wallet } = undefined;
undefined
也不与
null
.您需要,请调用
new PubSub(/*...*/)
使用正确的参数,或者使用默认参数值。
关于javascript - nodejs解构变量返回未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60892366/
我在寻找有关 JavaScript 解构的信息,并在 Packt Publication 的视频系列中找到了视频“解构赋值”。在视频的一开始,我看到了以下代码: var [a, b] = [1,2,3
知识渊博的人可以帮助我理解 Scalaz 的工作原理吗?和 co.有效吗?我是 Scalaz 的新手,有点迷失在探索中。 我想做的是在 List 中累积错误,例如 (v0 v1) foldLeft
Haskell 中的模式匹配可以用这种方式解构数字吗: f (n + 1) = n 我期望 ex 的前身:f 6 = 5、f 5 = 4 等。 我在这里找到了这种模式匹配用法: https://wik
我有一个与此类似的文件: const COLORS = { PRIMARY_COLOR: 'red', SECONDARY_COLOR: 'green' }; const APP = {
作为对 SO 问题的回答,我构建了一个循环函数,并构建了我迄今为止最复杂的解构,这奇迹般地起作用了: (defn fib? [a b & [c & r]] (if (= c (+ a b))
我对破坏感到困惑。 我在其中使用了 React,我们这样做了 const [ books, setBooks ] = useState([{a:'v'}] 和 const {books} = useC
我确定这在某个地方得到了回答,但我缺乏制定搜索的词汇。 #include class Thing { public: int value; Thing(); virtual ~Thing()
如果我在 javascript 中有这样一个对象: let obj = {b: 3, c: 4, d: 6} 如果我解构它,我可以很容易地得到不同的部分,例如,如果我这样做,我可以得到 c 和 d:
这个问题在这里已经有了答案: One-liner to take some properties from object in ES 6 (11 个回答) 2年前关闭。 我似乎不记得如何写这个解构模式
我有一个函数可以查询我的数据库中最近的 X 个条目,它返回一个 map 向量,如下所示: [{:itemID "item1" :category "stuff" :price 5} {:itemI
根据所选语言,我需要销毁对象并获得所需的值。 我该怎么做才能不破坏整个对象? const translate = { "navMenu1": { "en": "Menu 1",
我试图理解这种 ES6 解构。有人可以解释这行代码将编译成什么吗? const { loading, route: { pageName = 'default' } = {} } = this.pro
我有一个程序,可以输出这样的一些条件(这是实际输出,它是伪代码): if ( first occurance of 'AB' -0.5 ) * (( number of products viewe
Serilog的@的目的是什么?句法? 如果我运行以下命令: var dummy = new { Foo = "Bar", Date = DateTime.Now }; Log.Information
JSON 编码的数组从 PHP 传递到 HTML 文档。目前还不清楚如何将该数组解构为 javascript 可用的片段。例如,考虑以下 HTML: {"foo":[{"id":1},{"id":3}
我正在 Chrome 的控制台选项卡中尝试使用以下代码进行 JavaScript 解构,这给了我未捕获的语法错误:标识符“a”已被声明异常 o = { a: "foo", b: 12, c: "bar
我有一个 JavaSCript 对象 person,其中包含 id、name、phone 和 地址属性。我想修改属性名称并将它们放入新对象 personData 中。这可以一步完成吗?: 第 1 步(
有没有办法从 WPF 中获取 Geometry 实例的内部结构? 我需要转换一串用户输入的几何数据,例如 M10,100 C10,300 300,-200 300,100 Z 用于分离几何命令(移动、
我的代码中有一个 promise : req.getValidationResult() .then(result => { let errors = resu
我正在为 Apollo Client 生成 Flow 类型,我目前有这个: type FetchModuleQuery = {| // Fetch single module module:
我是一名优秀的程序员,十分优秀!