Dart 创建命令行工程 开发生产工具(以MacOS为例)
Dart 开发 命令行 工具还是挺舒服的,编译成二进制,丢到其他设备里面就可以跑,唯一可惜目前不支持交叉编译。
创建工程并配置
- 打开终端,cd 进入到任意文件目录
dart create -t console-full shopidstool
- 创建完,打开当前文件路径,将shopidstool工程拖到Android Studio 打开
- 简单配置下工程,点击左上角Android Studio -> Preference,如下图
- 设置下运行配置,点击Add Configurations
- 有用到的三方库,就在pubspec.yaml配置,代码写在bin/xxx.dart
Demo示例(爬取shopid比对,有更新通知并打印)
一个简单的工具demo,涉及到的知识点有网络请求数据,正则匹配,数组去重,md5加密字符串,本地文件读写
import 'dart:convert';
import 'dart:io';
import 'package:crypto/crypto.dart';
var fileurl1 =
'https://raw.githubusercontent.com/Aaron-lv/JavaScript/master/Task/jd_shop_sign.js';
var fileurl2 = 'https://raw.githubusercontent.com/liu1wei/sss/main/jd_dpqd.js';
Future<List<String>?> getFile(fileurl) async {
var httpClient = HttpClient();
var request = await httpClient.getUrl(Uri.parse(fileurl));
var response = await request.close();
if (response.statusCode == HttpStatus.ok) {
var responseBody = await response.transform(utf8.decoder).join();
var shopIdsReg = RegExp(r'[A-Z0-9]{32}');
var matchs = shopIdsReg.allMatches(responseBody);
var shopList = <String>[];
for (var match in matchs) {
var shopid = match.group(0);
shopList.add(shopid ??= '');
}
return shopList;
} else {
var result =
'Error getting IP address:\nHttp status ${response.statusCode}';
print(result);
return null;
}
}
Future getShops() {
var shops;
return Future.wait([getFile(fileurl1), getFile(fileurl2)]).then((value) {
var shops1 = value[0];
var shops2 = value[1];
shops = [...?shops1, ...?shops2];
return shops;
});
}
Future<String?> readShopIDsMd5() {
return File('shopidsMd5.txt').readAsLines().then((List<String> contents) {
String? res;
contents.forEach((ck) {
res = ck;
});
return res;
}).catchError((e) {
return '';
});
}
void writeMD5Res(String res) {
var file = File('shopidsMd5.txt');
var sink = file.openWrite();
sink.write(res);
sink.close();
}
void main(List<String> args) {
// 读取上次MD5
readShopIDsMd5().then((lastRes) {
getShops().then((shops) {
var resList = shops.toSet().toList();
var shopIDs = resList.join('&');
var md5Res = md5.convert(utf8.encode(shopIDs)).toString();
if (md5Res != lastRes) {
print(shopIDs);
print('数据已经更新,请手动替换');
writeMD5Res(md5Res);
} else {
print('数据无需更新');
exit(1);
}
});
});
}
编译成果物
- 点击Android Studio 底部 Terminal 打开终端
dart compile exe bin/shopidstool.dart -o ShopidsTool
文章目录
关闭
共有 0 条评论