首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在运行时加载文件

如何在运行时加载文件
EN

Stack Overflow用户
提问于 2022-07-14 19:53:26
回答 1查看 54关注 0票数 0

我正在使用nyxx库编写一个不和谐的机器人,并希望使用动态文件导入加载命令、信息和处理程序。但是,在谷歌搜索了5个小时之后,我没有找到任何东西来帮助我做到这一点。

在Node.js中,我可以使用require()import()来实现它:省道有类似的东西吗?

一个小代码片段,展示了我想要做的事情:

代码语言:javascript
运行
复制
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中注册它。)

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-07-15 02:58:48

理论上,您可以使用Isolate.spawnUri生成外部Dart程序,使其在自己的Isolate实例中运行,然后使用SendPort与主程序进行通信。

然而,它也有一些局限性。例如,在使用SendPort时,可以通过spawnUri发送哪些类型的对象是非常有限的,因为这两个程序不共享任何类型信息(与允许您发送自己的自定义类型的Isolate.spawn相比)。您可以在这里找到您可以发送的文档类型:

  • Null
  • bool
  • int
  • double
  • String
  • List或Map (其元素为these)
  • TransferableTypedData
  • SendPort
  • Capability

中的任何一个)

https://api.dart.dev/stable/2.17.6/dart-isolate/SendPort/send.html

但是它确实允许我们制定某种协议,并且您可以围绕它创建一些助手类来处理已知对象结构到例如Map<String, Object>的转换。

与Dart VM一起工作的一个小示例是:

您的命令实现为:command.dart

代码语言:javascript
运行
复制
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

代码语言:javascript
运行
复制
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来运行它,希望能得到:

代码语言:javascript
运行
复制
Got the following message: Hi julemand101. You got a message from my external command program!

如果要编译应用程序,可以执行以下操作。您需要编译command.dart,因为编译后的Dart程序不知道如何读取Dart代码。

代码语言:javascript
运行
复制
dart compile exe server.dart
dart compile aot-snapshot command.dart

您应该将Uri.file('command.dart')更改为Uri.file('command.aot'),因为aot-snapshot的文件扩展名是.aot

如果一切正常,你应该能够看到:

代码语言:javascript
运行
复制
> .\server.exe                
Got the following message: Hi julemand101. You got a message from my external command program!
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72985981

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档