我正在使用nyxx库编写一个不和谐的机器人,并希望使用动态文件导入加载命令、信息和处理程序。但是,在谷歌搜索了5个小时之后,我没有找到任何东西来帮助我做到这一点。
在Node.js中,我可以使用require()或import()来实现它:省道有类似的东西吗?
一个小代码片段,展示了我想要做的事情:
this.commands = new Collection();
fs.readdirSync('./src/commands').filter(( f ) => f.endsWith( '.js' )).forEach((file) => {
const command = require(`../commands/${file}`);
this.commands.set( command.info.name, command );
});这样做有可能吗?(我不喜欢为命令编写许多导入,并在lib中注册它。)
发布于 2022-07-15 02:58:48
理论上,您可以使用Isolate.spawnUri生成外部Dart程序,使其在自己的Isolate实例中运行,然后使用SendPort与主程序进行通信。
然而,它也有一些局限性。例如,在使用SendPort时,可以通过spawnUri发送哪些类型的对象是非常有限的,因为这两个程序不共享任何类型信息(与允许您发送自己的自定义类型的Isolate.spawn相比)。您可以在这里找到您可以发送的文档类型:
中的任何一个)
https://api.dart.dev/stable/2.17.6/dart-isolate/SendPort/send.html
但是它确实允许我们制定某种协议,并且您可以围绕它创建一些助手类来处理已知对象结构到例如Map<String, Object>的转换。
与Dart VM一起工作的一个小示例是:
您的命令实现为:command.dart
import 'dart:isolate';
void main(List<String> arguments, Map<String, Object> message) {
final userName = message['username'] as String;
final sendPort = message['port'] as SendPort;
sendPort.send('Hi $userName. '
'You got a message from my external command program!');
}调用命令的服务器:server.dart
import 'dart:isolate';
void main() {
final recievePort = ReceivePort();
recievePort.listen((message) {
print('Got the following message: $message');
recievePort.close();
});
Isolate.spawnUri(Uri.file('command.dart'), [], {
'username': 'julemand101',
'port': recievePort.sendPort,
});
}如果使用:dart server.dart来运行它,希望能得到:
Got the following message: Hi julemand101. You got a message from my external command program!如果要编译应用程序,可以执行以下操作。您需要编译command.dart,因为编译后的Dart程序不知道如何读取Dart代码。
dart compile exe server.dart
dart compile aot-snapshot command.dart您应该将Uri.file('command.dart')更改为Uri.file('command.aot'),因为aot-snapshot的文件扩展名是.aot。
如果一切正常,你应该能够看到:
> .\server.exe
Got the following message: Hi julemand101. You got a message from my external command program!https://stackoverflow.com/questions/72985981
复制相似问题