Catalyst

Deno 笔记

当我发现 js 写得比 python 熟的时候——反正都是脚本,做一些本地处理为什么不能用 js 呢?

然后我发现了 Deno。

部分特点有:

  • 安全,默认不开启敏感权限。
  • 本体只需要一个二进制文件,不像nodejs

安装

Deno 的官网

介绍:Deno 是一个简单、现代并安全的 JavaScript 和 TypeScript 运行时,使用 V8,利用 Rust 构建。

scoop安装:

scoop install deno

编写

Deno不使用npm而使用文件/网络 URL 导包。比如使用 deno-sqlite 库时的导入方法:

import { DB } from "https://deno.land/x/sqlite/mod.ts";

运行deno cache <file>缓存当前使用的包。包缓存在

  • Linux: $XDG_CACHE_HOME/deno 或者 $HOME/.cache/deno
  • Windows: %LOCALAPPDATA%/deno

Cli 相关

获取命令行参数:

Deno.args; //返回 Array

更高级的命令行:使用库 Denomander

使用Deno的 api:

Deno.stdin
Deno.stdout
import { readLines } from "https://deno.land/std@0.82.0/io/bufio.ts";
const notebook = await readLines(Deno.stdin);

文件操作

读取

const text = Deno.readTextFile("./a.txt");
text.then((response) => console.log(response));

写入

const write = Deno.writeTextFile("./hello.txt", "Hello World!");
write.then(() => console.log("File written to ./hello.txt"));

示例

使用 NPM 系包

Deno仅支持esm。可以借用类似 esm.sh(会给脚本做 polyfill)或者 Pika 的服务导入兼容包。

例:导入dayjs

import dayjs from "https://cdn.skypack.dev/dayjs?dts";
// 或者
import dayjs from "https://esm.sh/dayjs";

对于上述网站不支持的包,则尝试 使用 Deno 转换

import { createRequire } from "https://deno.land/std@0.106.0/node/module.ts";

const require = createRequire(import.meta.url);
// Loads native module polyfill.
const path = require("path");
// Loads extensionless module.
const cjsModule = require("./my_mod");
// Visits node_modules.
const leftPad = require("left-pad");

为了 VSCode 的提示功能,可以提前缓存写在文件里的导入包:

deno cache <file>

运行

设编写的脚本是index.ts

deno run index.ts

注意部分脚本运行所需要的 权限设置

#例:读写权限
deno run --allow-read --allow-write index.ts

编译为 exe

为了更方便在命令行中使用(或者分发),可以将脚本编译为可执行文件:

deno compile <权限 Flag> --output output.exe index.ts

执行二进制文件时就不用输入长长的权限 Flag 了。