示例工程 40-node-api-native-modules
40-node-api-native-modules/demo-02-abi-check/abi.ts
type Decision = {
mode: "native" | "fallback" | "refuse";
reason: string;
};
function decide(input: {
exists: boolean;
platformMatches: boolean;
archMatches: boolean;
napiVersion: number;
requiredNapi: number;
exportsOk: boolean;
nativeRequired: boolean;
}): Decision {
if (!input.exists) {
return input.nativeRequired
? { mode: "refuse", reason: "缺少必需的原生模块" }
: { mode: "fallback", reason: "原生模块不存在,使用 JS" };
}
if (!input.platformMatches || !input.archMatches) {
return { mode: "fallback", reason: "平台或架构不匹配" };
}
if (input.napiVersion < input.requiredNapi) {
return { mode: "fallback", reason: "N-API 版本过低" };
}
if (!input.exportsOk) {
return { mode: "fallback", reason: "导出不完整" };
}
return { mode: "native", reason: "加载条件满足" };
}
const base = {
exists: true,
platformMatches: true,
archMatches: true,
napiVersion: 10,
requiredNapi: 8,
exportsOk: true,
nativeRequired: false,
};
const cases = {
native: decide(base),
missing: decide({ ...base, exists: false }),
missingRequired: decide({ ...base, exists: false, nativeRequired: true }),
wrongArch: decide({ ...base, archMatches: false }),
oldNapi: decide({ ...base, napiVersion: 7 }),
badExports: decide({ ...base, exportsOk: false }),
};
const ok =
cases.native.mode === "native" &&
cases.missing.mode === "fallback" &&
cases.missingRequired.mode === "refuse" &&
cases.wrongArch.mode === "fallback" &&
cases.oldNapi.mode === "fallback" &&
cases.badExports.mode === "fallback";
console.log(
JSON.stringify({
evt: "smoke",
ok,
abi: {
platform: process.platform,
arch: process.arch,
modules: process.versions.modules,
napi: process.versions.napi,
node: process.versions.node,
},
cases,
}),
);