gpt4 book ai didi

javascript - 我如何在 NodeJS 中正确地要求文件?

转载 作者:行者123 更新时间:2023-11-30 19:38:04 24 4
gpt4 key购买 nike

<分区>

我正在使用 NodeJS 和 ExpressJS 设置区 block 链客户端-服务器网络。我让服务器成功运行并且区 block 链自行运行。但是我在将两者结合起来时遇到了一些问题。首先,这是我的项目结构:

node_p2p/
node_modules/
...
public/
block.js
client.js
index.html
package-lock.json
package.json
server.js

我遇到的实际问题是,我想在 client.js 文件中包含 block.js,但我总是得到 ReferenceError: require is未定义 行,我将 block.js 包含到 client.js 中:

var block = require('./block.js');

我已经尝试了以下变体,但它们都产生了相同的错误(这是意料之中的,因为 require 目录是相对于调用 require 的文件,但我还是尝试了它们,以防万一):

var block = require('../public/block.js');
var block = require('../public/block');
var block = require('./public/block.js');
var block = require('./public/block');
var block = require('/public/block.js');
var block = require('/public/block');
var block = require('../block.js');
var block = require('../block');
var block = require('./block.js');
var block = require('./block');
var block = require('block.js');
var block = require('block');

这是block.js的代码:

const SHA256 = require ('crypto-js/sha256');

class Block{
constructor(...){...}
...
}

class Blockhain{
constructor(...){...}
...
}

module.exports = {
Blockchain: function(){
return new Blockchain();
}
}

其次,client.js:

var socket = io.connect('http://localhost:3000');
var block = require('./block.js');

socket.on('client', showData);
socket.on('clientno', showData);
socket.on('newclient', showData);
function showData(data) {
console.log(data);
}

var nascoin = new block.Blockchain();

最后,server.js:

var express = require('express');

var app = express();
var server = app.listen(3000);

app.use(express.static('public'));

console.log("server running!");

var socket = require('socket.io');
var io = socket(server);

io.sockets.on('connection', newConnection);

var client_counter = 0;

function newConnection(socket) {
console.log('new conn: ' + socket.id);
client_counter++;

socket.emit('client', 'your client name: ' + socket.id);
socket.emit('clientno', 'you are client no.: ' + client_counter);
socket.broadcast.emit('newclient', 'new client has joined the fray');
socket.on('server', function(data) {
console.log(data);
});
}

我什至不知道我还能做什么,要么我就是那么笨,要么就是那么瞎......

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com