@aabuhijleh/native-reg 中文文档教程

发布于 5年前 浏览 28 项目主页 更新于 3年前

native-reg

用于 Windows 注册表访问的进程本机模块。

Example

const reg = require('native-reg');

const key = reg.openKey(
  reg.HKCU,
  'Software\\MyCompany\\MySoftware',
  reg.Access.ALL_ACCESS);

const version = reg.getValue(key, 'Install', 'Version');

if (isOldVersion(version)) {
    reg.deleteTree(key, 'Install');

    const installKey = reg.createKey(key, 'Install', reg.Access.ALL_ACCESS);
    reg.setValue(installKey, 'Version', newVersion);
    // ...
    reg.closeKey(installKey);
}

reg.closeKey(key);

API

阅读 index.ts 和链接的 Windows 文档以获取完整详细信息。

Errors

API 最初使用标准节点 assert 库验证参数:

try {
  // Should not be 'HKLM', but reg.HKLM or reg.HKEY.LOCAL_MACHINE
  reg.openKey('HKLM', 'SOFTWARE\\Microsoft\\Windows', reg.Access.READ);
  assert.fail();
} catch (e) {
  assert(e instanceof require('assert').AssertionError);
}

如果包装的 Windows API 返回错误,但有几个例外 通常非失败错误(例如键不存在)被抛出为 JS Errors 带有一般错误消息,例如:Access is denied.,但额外的 标准的 errnosyscall 属性,例如,一个常见的错误是尝试 在 reg.HKLM 上使用 Access.ALL_ACCESS,您需要 UAC 提升:

try {
  // Assuming you are not running as administrator!
  reg.openKey(reg.HKLM, 'SOFTWARE\\Microsoft\\Windows', reg.Access.ALL_ACCESS);
  assert.fail();
} catch (e) {
  assert.strictEqual(e.message, 'Access is denied.');
  assert.strictEqual(e.errno, 5);
  assert.strictEqual(e.syscall, 'RegOpenKeyExW');
}

Constants

此库使用 Typescript enum 作为常量,这会生成一个 双向名称 <-> 值映射。

例如:Access.SET_VALUE0x0002Access[2]"SET_VALUE"

HKEY enum

导出一组预定义的 HKEY

createKeyopenKeyloadAppKeyopenCurrentUser 将为 HKEY 返回其他值, 目前是具有单个属性 native 和 native 的对象 HKEY 句柄作为 V8 External 值,用于其他本机包,或 null 关闭后。 对于这些值,您可以在完成清理后调用 closeKey 早,但如果您选择不这样做,它们将被垃圾收集器关闭。

export enum HKEY {
  CLASSES_ROOT                   = 0x80000000,
  CURRENT_USER                   = 0x80000001,
  LOCAL_MACHINE                  = 0x80000002,
  USERS                          = 0x80000003,
  PERFORMANCE_DATA               = 0x80000004,
  PERFORMANCE_TEXT               = 0x80000050,
  PERFORMANCE_NLSTEXT            = 0x80000060,
  CURRENT_CONFIG                 = 0x80000005,
  DYN_DATA                       = 0x80000006,
  CURRENT_USER_LOCAL_SETTINGS    = 0x80000007,
}
Shorthands

还导出标准的简写 HKEY 名称:

export const HKCR = HKEY.CLASSES_ROOT;
export const HKCU = HKEY.CURRENT_USER;
export const HKLM = HKEY.LOCAL_MACHINE;
export const HKU = HKEY.USERS;
isHKEY

如果参数是一个有效的 HKEY,Helper 将返回。 大多数 API 都会抛出 如果使用不为此返回 true 的 hkey,则会出现断言错误。

有效的 HKEY 值为,

  • The values of the HKEY enum
  • Objects returned from createKey, openKey, loadAppKey and openCurrentUser
  • External values that represent HKEYs (for example, from another node addon)
  • Non-0 32-bit values that represent the pointer value of HKEYs (for example, from another node addon) - not that this is unreliable on 64-bit applications, and should be avoided.
export function isHKEY(hkey: any): boolean;

Access enum

指定对打开或创建的密钥进行访问检查。 并不总是强制执行 打开的密钥:

某些注册表操作针对密钥的安全描述符执行访问检查,而不是在获取密钥句柄时指定的访问掩码。 例如,即使使用 KEYREAD 的 samDesired 打开一个键,如果键的安全描述符允许,它也可以用于创建注册表键。 相比之下,RegSetValueEx 函数特别要求使用 KEYSET_VALUE 访问权限打开密钥。

// from https://docs.microsoft.com/en-nz/windows/desktop/SysInfo/registry-key-security-and-access-rights
export enum Access {
  // Specific rights
  QUERY_VALUE         = 0x0001,
  SET_VALUE           = 0x0002,
  CREATE_SUB_KEY      = 0x0004,
  ENUMERATE_SUB_KEYS  = 0x0008,
  NOTIFY              = 0x0010,
  CREATE_LINK         = 0x0020,

  // WOW64. See https://docs.microsoft.com/en-nz/windows/desktop/WinProg64/accessing-an-alternate-registry-view
  WOW64_64KEY         = 0x0100,
  WOW64_32KEY         = 0x0200,

  // Generic rights.
  READ              = 0x2_0019,
  WRITE             = 0x2_0006,
  EXECUTE           = READ,

  ALL_ACCESS        = 0xF_003F,
}

ValueType enum

注册表值的类型。

export enum ValueType  {
  NONE                       = 0, // No value type
  SZ                         = 1, // Unicode nul terminated string
  EXPAND_SZ                  = 2, // Unicode nul terminated string
                                  // (with environment variable references)
  BINARY                     = 3, // Free form binary
  DWORD                      = 4, // 32-bit number
  DWORD_LITTLE_ENDIAN        = 4, // 32-bit number (same as REG_DWORD)
  DWORD_BIG_ENDIAN           = 5, // 32-bit number
  LINK                       = 6, // Symbolic Link (unicode)
  MULTI_SZ                   = 7, // Multiple Unicode strings
  RESOURCE_LIST              = 8, // Resource list in the resource map
  FULL_RESOURCE_DESCRIPTOR   = 9, // Resource list in the hardware description
  RESOURCE_REQUIREMENTS_LIST = 10,
  QWORD                      = 11, // 64-bit number
  QWORD_LITTLE_ENDIAN        = 11, // 64-bit number (same as REG_QWORD)
}

Raw APIs

这些 API 相当直接地包装了链接的 Windows API,只抽象了一些 分配和一般使用方式。

例外是 enumKeyNamesenumValueNames 迭代以构建列表并仅返回名称,而不返回其他属性。

Value

queryValueRawgetValueRaw 返回的原始注册表值 只是 Node Buffer,带有来自 ValueType 的附加 type 属性:

export type Value = Buffer & { type: ValueType };

createKey

Wraps RegCreateKeyExW

创建指定的注册表项。 如果密钥已经存在,函数将打开它。 请注意,键名不区分大小写。

您必须对结果调用 closeKey 以进行清理。

export function createKey(
  hkey: HKEY,
  subKey: string,
  access: Access,
  options: CreateKeyOptions = 0,
): HKEY;

openKey

Wraps RegOpenKeyExW

打开指定的注册表项。 请注意,键名不区分大小写。

如果 hkey 下不存在 subKey,则返回 null

您必须对结果调用 closeKey 以进行清理。

export function openKey(
  hkey: HKEY,
  subKey: string,
  access: Access,
  options: OpenKeyOptions = 0,
): HKEY | null;

loadAppKey

Wraps RegLoadAppKeyW

加载指定的注册表配置单元作为应用程序配置单元。

您必须对结果调用 closeKey 以进行清理。

export function loadAppKey(file: string, access: Access): HKEY;

openCurrentUser

包装 RegOpenCurrentUser

检索句柄到当前线程正在模拟的用户的 HKEY_CURRENT_USER 键。

仅当您有权访问 Windows 用户模拟时才有意义。 也许看看我的 目前正在开发 Windows 用户帐户包

您必须对结果调用 closeKey 以进行清理。

export function openCurrentUser(access: Access): HKEY;

enumKeyNames

包装 RegEnumKeyExW 迭代以获取键的子键名称。

枚举指定的打开注册表项的子项。

export function enumKeyNames(hkey: HKEY): string[];

enumValueNames

包装 RegEnumValueW 迭代以获取键的值名称。

枚举指定的打开注册表项的值。

export function enumValueNames(hkey: HKEY): string[];

queryValueRaw

包装 RegQueryValueExW 无需额外解析。

检索与打开的注册表项关联的指定值名称的类型和数据。

您可能想改用 queryValue

如果 hkey 下不存在 valueName,则返回 null

export function queryValueRaw(hkey: HKEY, valueName: string): Value | null;

getValueRaw

包装 RegGetValueExW 无需额外解析。

检索指定注册表值的类型和数据。

您可能想改用 getValue

如果 hkey 下不存在 subKeyvalueName,则返回 null

export function getValueRaw(
  hkey: HKEY,
  subKey: string,
  valueName: string,
  flags: GetValueFlags = 0,
): Value | null;

deleteKey

Wraps RegDeleteKeyW

删除一个子项及其价值观。 请注意,键名不区分大小写。

如果键在删除之前存在,则返回 true。

export function deleteKey(hkey: HKEY, subKey: string): boolean;

deleteTree

Wraps RegDeleteTreeW

删除子项和递归指定键的值。

如果键在删除之前存在,则返回 true。

export function deleteTree(hkey: HKEY, subKey: string): boolean;

deleteKeyValue

Wraps RegDeleteKeyValueW

删除指定的来自指定注册表项和子项的值。

如果该值在删除之前存在,则返回 true。

export function deleteKeyValue(
  hkey: HKEY,
  subKey: string,
  valueName: string,
): boolean;

deleteValue

Wraps RegDeleteValueW

删除命名来自指定注册表项的值。 请注意,值名称不区分大小写。

如果该值在删除之前存在,则返回 true。

export function deleteValue(hkey: HKEY, valueName: string): boolean;

closeKey

Wraps RegCloseKey

关闭句柄到指定的注册表项。

为方便起见,允许和忽略 nullundefined 值。

export function closeKey(hkey: HKEY | null | undefined): void;

Format helpers

parseValue

返回常见 Value 类型的 JS 原生值:

  • SZ, EXPAND_SZ -> string
  • BINARY -> Buffer
  • DWORD / DWORD_LITTLE_ENDIAN -> number
  • DWORD_BIG_ENDIAN -> number
  • MULTI_SZ -> string[]

如果类型不是上述类型之一,则抛出!

为方便起见,通过 null 使缺失值没有 要特别对待。

export type ParsedValue = number | string | string[] | Buffer;
export function parseValue(value: Value | null): ParsedValue | null;

parseString

解析 SZEXPAND_SZ(等)注册表值。

export function parseString(value: Buffer): string;

parseString

解析 SZEXPAND_SZ(等)注册表值。

export function parseString(value: Buffer): string;

parseMultiString

解析 MULTI_SZ 注册表值。

export function parseMultiString(value: Buffer): string[];

formatString

将字符串格式化为 SZEXPAND_SZ(等)格式。

export function formatString(value: string): Buffer;

formatMultiString

string 的数组格式化为 MULTI_SZ 格式。

export function formatMultiString(values: string[]): Buffer;

formatDWORD

number 格式化为 DWORD / DWORD_LITTLE_ENDIAN 格式。

export function formatDWORD(value: number): Buffer;

formatQWORD

number 格式化为 QWORD 格式。

export function formatQWORD(value: number): Buffer;

Formatted value APIs

这些 API 使用格式化助手包装原始值 API。

setValue{Type}

使用匹配的 {Type} 和格式化值设置注册表值。

例如,setValueSZsetValueRaw(hkey, valueName, ValueType.SZ, formatString(value))

export function setValueSZ(
  hkey: HKEY,
  valueName: string,
  value: string,
): void;
export function setValueEXPAND_SZ(
  hkey: HKEY,
  valueName: string,
  value: string,
): void;
export function setValueMULTI_SZ(
  hkey: HKEY,
  valueName: string,
  value: string[],
): void;
export function setValueDWORD(
  hkey: HKEY,
  valueName: string,
  value: number,
): void;
export function setValueQWORD(
  hkey: HKEY,
  valueName: string,
  value: number,
): void;

getValue

getValueRaw 包装在 parseValue 中。

export function getValue(
  hkey: HKEY,
  subKey: string,
  valueName: string,
  flags: GetValueFlags = 0,
): ParsedValue | null;

queryValue

queryValueRaw 包装在 parseValue 中。

export function queryValue(hkey: HKEY, valueName: string): ParsedValue | null;

native-reg

In process native module for Windows registry access.

Example

const reg = require('native-reg');

const key = reg.openKey(
  reg.HKCU,
  'Software\\MyCompany\\MySoftware',
  reg.Access.ALL_ACCESS);

const version = reg.getValue(key, 'Install', 'Version');

if (isOldVersion(version)) {
    reg.deleteTree(key, 'Install');

    const installKey = reg.createKey(key, 'Install', reg.Access.ALL_ACCESS);
    reg.setValue(installKey, 'Version', newVersion);
    // ...
    reg.closeKey(installKey);
}

reg.closeKey(key);

API

Read index.ts and linked Windows documentation for full details.

Errors

The API initially validates the arguments with the standard node assert library:

try {
  // Should not be 'HKLM', but reg.HKLM or reg.HKEY.LOCAL_MACHINE
  reg.openKey('HKLM', 'SOFTWARE\\Microsoft\\Windows', reg.Access.READ);
  assert.fail();
} catch (e) {
  assert(e instanceof require('assert').AssertionError);
}

If the wrapped Windows API returns an error, with a couple of exceptions for commonly non-failure errors (e.g. key does not exist), are thrown as JS Errors with the generic error message, e.g.: Access is denied., but additional standard errno and syscall properties, for example, a common error is trying to use Access.ALL_ACCESS on reg.HKLM, which you need UAC elevation for:

try {
  // Assuming you are not running as administrator!
  reg.openKey(reg.HKLM, 'SOFTWARE\\Microsoft\\Windows', reg.Access.ALL_ACCESS);
  assert.fail();
} catch (e) {
  assert.strictEqual(e.message, 'Access is denied.');
  assert.strictEqual(e.errno, 5);
  assert.strictEqual(e.syscall, 'RegOpenKeyExW');
}

Constants

This library uses Typescript enums for constants, this generates a two way name <-> value mapping.

For example: Access.SET_VALUE is 0x0002, and Access[2] is "SET_VALUE".

HKEY enum

Exports the set of predefined HKEYs.

createKey, openKey, loadAppKey and openCurrentUser will return other values for HKEYs, which at the moment are objects with a single property native with the native HKEY handle as a V8 External value, for use in other native packages, or null after it is closed. For these values you can call closeKey once you are done to clean up early, but they will be closed by the garbage collector if you chose not to.

export enum HKEY {
  CLASSES_ROOT                   = 0x80000000,
  CURRENT_USER                   = 0x80000001,
  LOCAL_MACHINE                  = 0x80000002,
  USERS                          = 0x80000003,
  PERFORMANCE_DATA               = 0x80000004,
  PERFORMANCE_TEXT               = 0x80000050,
  PERFORMANCE_NLSTEXT            = 0x80000060,
  CURRENT_CONFIG                 = 0x80000005,
  DYN_DATA                       = 0x80000006,
  CURRENT_USER_LOCAL_SETTINGS    = 0x80000007,
}
Shorthands

Also exports the standard shorthand HKEY names:

export const HKCR = HKEY.CLASSES_ROOT;
export const HKCU = HKEY.CURRENT_USER;
export const HKLM = HKEY.LOCAL_MACHINE;
export const HKU = HKEY.USERS;
isHKEY

Helper returns if the argument is a valid-looking HKEY. Most APIs will throw an assertion error if hkey that does not return true for this is used.

Valid HKEY values are,

  • The values of the HKEY enum
  • Objects returned from createKey, openKey, loadAppKey and openCurrentUser
  • External values that represent HKEYs (for example, from another node addon)
  • Non-0 32-bit values that represent the pointer value of HKEYs (for example, from another node addon) - not that this is unreliable on 64-bit applications, and should be avoided.
export function isHKEY(hkey: any): boolean;

Access enum

Specifies access checks for opened or created keys. Not always enforced for opened keys:

Certain registry operations perform access checks against the security descriptor of the key, not the access mask specified when the handle to the key was obtained. For example, even if a key is opened with a samDesired of KEYREAD, it can be used to create registry keys if the key's security descriptor permits. In contrast, the RegSetValueEx function specifically requires that the key be opened with the KEYSET_VALUE access right.

// from https://docs.microsoft.com/en-nz/windows/desktop/SysInfo/registry-key-security-and-access-rights
export enum Access {
  // Specific rights
  QUERY_VALUE         = 0x0001,
  SET_VALUE           = 0x0002,
  CREATE_SUB_KEY      = 0x0004,
  ENUMERATE_SUB_KEYS  = 0x0008,
  NOTIFY              = 0x0010,
  CREATE_LINK         = 0x0020,

  // WOW64. See https://docs.microsoft.com/en-nz/windows/desktop/WinProg64/accessing-an-alternate-registry-view
  WOW64_64KEY         = 0x0100,
  WOW64_32KEY         = 0x0200,

  // Generic rights.
  READ              = 0x2_0019,
  WRITE             = 0x2_0006,
  EXECUTE           = READ,

  ALL_ACCESS        = 0xF_003F,
}

ValueType enum

Types for registry values.

export enum ValueType  {
  NONE                       = 0, // No value type
  SZ                         = 1, // Unicode nul terminated string
  EXPAND_SZ                  = 2, // Unicode nul terminated string
                                  // (with environment variable references)
  BINARY                     = 3, // Free form binary
  DWORD                      = 4, // 32-bit number
  DWORD_LITTLE_ENDIAN        = 4, // 32-bit number (same as REG_DWORD)
  DWORD_BIG_ENDIAN           = 5, // 32-bit number
  LINK                       = 6, // Symbolic Link (unicode)
  MULTI_SZ                   = 7, // Multiple Unicode strings
  RESOURCE_LIST              = 8, // Resource list in the resource map
  FULL_RESOURCE_DESCRIPTOR   = 9, // Resource list in the hardware description
  RESOURCE_REQUIREMENTS_LIST = 10,
  QWORD                      = 11, // 64-bit number
  QWORD_LITTLE_ENDIAN        = 11, // 64-bit number (same as REG_QWORD)
}

Raw APIs

These APIs fairly directly wrap the Windows API linked, only abstracting some of the allocation and general usage style.

The exception is enumKeyNames and enumValueNames which iterate to build a list and only return the names, and not other properties.

Value

Raw registry values returned from queryValueRaw and getValueRaw are simply Node Buffers with an additional type property from ValueType:

export type Value = Buffer & { type: ValueType };

createKey

Wraps RegCreateKeyExW

Creates the specified registry key. If the key already exists, the function opens it. Note that key names are not case sensitive.

You must call closeKey on the result to clean up.

export function createKey(
  hkey: HKEY,
  subKey: string,
  access: Access,
  options: CreateKeyOptions = 0,
): HKEY;

openKey

Wraps RegOpenKeyExW

Opens the specified registry key. Note that key names are not case sensitive.

Returns null if subKey does not exist under hkey.

You must call closeKey on the result to clean up.

export function openKey(
  hkey: HKEY,
  subKey: string,
  access: Access,
  options: OpenKeyOptions = 0,
): HKEY | null;

loadAppKey

Wraps RegLoadAppKeyW

Loads the specified registry hive as an application hive.

You must call closeKey on the result to clean up.

export function loadAppKey(file: string, access: Access): HKEY;

openCurrentUser

Wraps RegOpenCurrentUser

Retrieves a handle to the HKEY_CURRENT_USER key for the user the current thread is impersonating.

Only makes sense to use if you have access to Windows user impersonation. Maybe take a look at my currently WIP Windows user account package.

You must call closeKey on the result to clean up.

export function openCurrentUser(access: Access): HKEY;

enumKeyNames

Wraps RegEnumKeyExW iterated to get the sub key names for a key.

Enumerates the subkeys of the specified open registry key.

export function enumKeyNames(hkey: HKEY): string[];

enumValueNames

Wraps RegEnumValueW iterated to get the value names for a key.

Enumerates the values for the specified open registry key.

export function enumValueNames(hkey: HKEY): string[];

queryValueRaw

Wraps RegQueryValueExW without additional parsing.

Retrieves the type and data for the specified value name associated with an open registry key.

You may want to use queryValue instead.

Returns null if valueName does not exist under hkey.

export function queryValueRaw(hkey: HKEY, valueName: string): Value | null;

getValueRaw

Wraps RegGetValueExW without additional parsing.

Retrieves the type and data for the specified registry value.

You may want to use getValue instead.

Returns null if subKey or valueName does not exist under hkey.

export function getValueRaw(
  hkey: HKEY,
  subKey: string,
  valueName: string,
  flags: GetValueFlags = 0,
): Value | null;

deleteKey

Wraps RegDeleteKeyW

Deletes a subkey and its values. Note that key names are not case sensitive.

Returns true if the key existed before it was deleted.

export function deleteKey(hkey: HKEY, subKey: string): boolean;

deleteTree

Wraps RegDeleteTreeW

Deletes the subkeys and values of the specified key recursively.

Returns true if the key existed before it was deleted.

export function deleteTree(hkey: HKEY, subKey: string): boolean;

deleteKeyValue

Wraps RegDeleteKeyValueW

Removes the specified value from the specified registry key and subkey.

Returns true if the value existed before it was deleted.

export function deleteKeyValue(
  hkey: HKEY,
  subKey: string,
  valueName: string,
): boolean;

deleteValue

Wraps RegDeleteValueW

Removes a named value from the specified registry key. Note that value names are not case sensitive.

Returns true if the value existed before it was deleted.

export function deleteValue(hkey: HKEY, valueName: string): boolean;

closeKey

Wraps RegCloseKey

Closes a handle to the specified registry key.

For convenience, null or undefined values are allowed and ignored.

export function closeKey(hkey: HKEY | null | undefined): void;

Format helpers

parseValue

Returns the JS-native value for common Value types:

  • SZ, EXPAND_SZ -> string
  • BINARY -> Buffer
  • DWORD / DWORD_LITTLE_ENDIAN -> number
  • DWORD_BIG_ENDIAN -> number
  • MULTI_SZ -> string[]

Throws if the type is not one of the above!

For convenience, passes through null so missing values don't have to be specially treated.

export type ParsedValue = number | string | string[] | Buffer;
export function parseValue(value: Value | null): ParsedValue | null;

parseString

Parses SZ and EXPAND_SZ (etc.) registry values.

export function parseString(value: Buffer): string;

parseString

Parses SZ and EXPAND_SZ (etc.) registry values.

export function parseString(value: Buffer): string;

parseMultiString

Parses MULTI_SZ registry values.

export function parseMultiString(value: Buffer): string[];

formatString

Formats a string to SZ, EXPAND_SZ (etc.) format.

export function formatString(value: string): Buffer;

formatMultiString

Formats an array of strings to MULTI_SZ format.

export function formatMultiString(values: string[]): Buffer;

formatDWORD

Formats a number to DWORD / DWORD_LITTLE_ENDIAN format.

export function formatDWORD(value: number): Buffer;

formatQWORD

Formats a number to QWORD format.

export function formatQWORD(value: number): Buffer;

Formatted value APIs

These APIs wrap the raw value APIs with the formatting helpers.

setValue{Type}

Sets the registry value with a matching {Type} and formatted value.

For example, setValueSZ is setValueRaw(hkey, valueName, ValueType.SZ, formatString(value)).

export function setValueSZ(
  hkey: HKEY,
  valueName: string,
  value: string,
): void;
export function setValueEXPAND_SZ(
  hkey: HKEY,
  valueName: string,
  value: string,
): void;
export function setValueMULTI_SZ(
  hkey: HKEY,
  valueName: string,
  value: string[],
): void;
export function setValueDWORD(
  hkey: HKEY,
  valueName: string,
  value: number,
): void;
export function setValueQWORD(
  hkey: HKEY,
  valueName: string,
  value: number,
): void;

getValue

Wraps getValueRaw in parseValue.

export function getValue(
  hkey: HKEY,
  subKey: string,
  valueName: string,
  flags: GetValueFlags = 0,
): ParsedValue | null;

queryValue

Wraps queryValueRaw in parseValue.

export function queryValue(hkey: HKEY, valueName: string): ParsedValue | null;
更多

友情链接

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文