发布于 2022-03-20 18:18:47
正如您已经注意到的,@types/node只包括webcrypto接口的存根。解决方法之一是扩展crypto模块声明,从DOM类型定义将webcrypto.subtle声明为SubtleCrypto:
// src/types/index.d.ts
declare module "crypto" {
namespace webcrypto {
const subtle: SubtleCrypto;
}
}这允许编写如下模块:
// src/digest.ts:
import * as crypto from "crypto";
// subtle has type SubtleCrypto, from the DOM type definitions
const { subtle } = crypto.webcrypto;
// Generate a cryptographic digest of the given message
export async function digest(message?: string, algorithm = "SHA-512") {
const encoder = new TextEncoder();
const data = encoder.encode(message);
const hash = await subtle.digest(algorithm, data);
return hash;
}要使用SubtleCrypto,项目必须通过将dom添加到tsconfig.json中的lib数组来启用DOM类型定义。例如,安装了以下软件包:
$ npm install -D typescript@4.6 @types/node@17 @tsconfig/node17和一个tsconfig.json,包含:
{
"extends": "@tsconfig/node17/tsconfig.json",
"compilerOptions": {
"lib": ["dom"],
"outDir": "dist",
"typeRoots": ["./node_modules/@types", "./src/types"]
},
"include": ["src/**/*"],
"exclude": ["dist", "node_modules"]
}您可以编写一个入口点,调用digest并打印结果:
// src/index.ts
import { digest } from "./digest";
const message = "Hello, World!";
(async () => {
const digestBuffer = await digest(message);
console.log(Buffer.from(new Uint8Array(digestBuffer)).toString("hex"));
})();它构建并运行,如:
$ npx tsc && node dist/index.js
374d794a95cdcfd8b35993185fef9ba368f160d8daf432d08ba9f1ed1e5abe6cc69291e0fa2fe0006a52570ef18c19def4e617c33ce52ef0a6e5fbe318cb0387https://stackoverflow.com/questions/71525466
复制相似问题