Initial commit

This commit is contained in:
2025-03-07 19:22:02 +01:00
commit 4a98255d83
55743 changed files with 5280367 additions and 0 deletions
+16
View File
@@ -0,0 +1,16 @@
lib-cov
*.seed
*.log
*.csv
*.dat
*.out
*.pid
*.gz
pids
logs
results
npm-debug.log
/docs
/node_modules
+122
View File
@@ -0,0 +1,122 @@
[![NPM](https://nodei.co/npm/winreg.png?downloads=true&stars=true)](https://nodei.co/npm/winreg/)
[![Build status](https://ci.appveyor.com/api/projects/status/sxal24cfk9nlmib9?svg=true)](https://ci.appveyor.com/project/fresc81/node-winreg) [![Dependency Status](https://david-dm.org/fresc81/node-winreg.svg)](https://david-dm.org/fresc81/node-winreg) [![devDependency Status](https://david-dm.org/fresc81/node-winreg/dev-status.svg)](https://david-dm.org/fresc81/node-winreg#info=devDependencies) [![Join the chat at https://gitter.im/fresc81/node-winreg](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/fresc81/node-winreg?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
# node-winreg #
node module that provides access to the Windows Registry through the REG commandline tool
## Installation ##
The following command installs node-winreg.
```shell
npm install winreg
```
If you prefer to install _without the delopement tools used to generate the HTML documentation_ (into a production environment for example) you should use the following command.
```shell
npm install winreg --production
```
Note that the development dependencies will not be installed if this package was installed as a dependency of another package.
## Documentation ##
The documentation is generated using [jsdoc](http://github.com/jsdoc3/jsdoc "jsdoc Website") with the [docstrap template](http://docstrap.github.io/docstrap "docstrap website"). You can view the API documentation [online](http://fresc81.github.io/node-winreg "online documentation"), download the latest documentation or generate it from the sourcecode.
### Online Documentation ###
View the latest docs [online](http://fresc81.github.io/node-winreg "online documentation").
### Download Documentation ###
To download the latest docs from GIT the following command is used.
```shell
npm run-script download-docs
```
### Generate Documentation ###
To generate the docs from the sources you can use the following command.
```shell
npm run-script generate-docs
```
Note that generating the docs requires the development dependencies to be installed.
## Example Usage ##
Let's start with an example. The code below lists the autostart programs of the current user.
```javascript
var Registry = require('winreg')
, regKey = new Registry({ // new operator is optional
hive: Registry.HKCU, // open registry hive HKEY_CURRENT_USER
key: '\\Software\\Microsoft\\Windows\\CurrentVersion\\Run' // key containing autostart programs
})
// list autostart programs
regKey.values(function (err, items /* array of RegistryItem */) {
if (err)
console.log('ERROR: '+err);
else
for (var i=0; i<items.length; i++)
console.log('ITEM: '+items[i].name+'\t'+items[i].type+'\t'+items[i].value);
});
```
## Troubleshooting ##
### Access to restricted keys ###
Since Windows Vista access to certain Registry Hives (HKEY_LOCAL_MACHINE or short HKLM for example) is restricted to processes that run in a security elevated context even if the user that starts the process is an admin. You can start a console within that context by right clicking the console shortcut and selecting the item with the shield icon called "Run as administrator" from the context menu.
Under some rare circumstances access to Registry Hives or particular keys may also be blocked by some antivirus programs or the Windows Group Policy Editor (google for gpedit.msc).
You can also use the regedit.exe tool shipped with Windows to check if you actually have access.
### Processing UTF-8 data ###
The Microsoft Windows console isn't capable of handling UTF-8 encoded text unless you set it up properly. If you see weird question marks for certain characters, it's probhably a problem with the encoding.
By default the console is setup to use an encoding that suits the language of the Windows operating system installation. Windows uses codepages to specify encodings for the console. The codepage is a unique number which is assigned to each encoding.
If you want to query the currently selected codepage you can type the command <code>chcp</code> (w/o parameters). To set a new codepage (UTF-8 for this example) you pass the codepage number as the only argument to <code>chcp</code>. The codepage value for UTF-8 is 65001.
You can easily do this from within your nodejs script by using the <code>child_process.execSync(...)</code> function like the following example shows.
```javascript
var execSync = require('child_process').execSync;
console.log(execSync('chcp').toString());
console.log(execSync('chcp 65001').toString());
```
An even better approach would be to extract and store the value returned by a call to <code>chcp</code> prior setting the console to UTF-8 and resetting the codepage after your script is done.
## License ##
This project is released under [BSD 2-Clause License](http://opensource.org/licenses/BSD-2-Clause).
Copyright (c) 2016, Paul Bottin All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+45
View File
@@ -0,0 +1,45 @@
{
"tags": {
"allowUnknownTags": false
},
"opts": {
"template": "./node_modules/ink-docstrap/template",
"encoding": "utf8",
"destination": "./docs/",
"recurse": true,
"private": true,
"lenient": true,
"verbose": true,
"nocolor": true
},
"source": {
"include": [
"./lib",
"./README.md"
],
"includePattern": ".+\\.js(doc)?$"
},
"plugins": [
"plugins/markdown"
],
"templates": {
"syntaxTheme": "dark",
"cleverLinks": true,
"monospaceLinks": true,
"default": {
"outputSourceFiles": true
},
"systemName": "node-winreg",
"footer": "<style>#forkongithub {display:none;}#forkongithub a{background:#000;color:#fff;text-decoration:none;font-family:arial, sans-serif;text-align:center;font-weight:bold;padding:5px 40px;font-size:1rem;line-height:2rem;position:relative;transition:0.5s;}#forkongithub a:hover{background:#33B5E5;color:#fff;}#forkongithub a::before,#forkongithub a::after{content:\"\";width:100%;display:block;position:absolute;top:1px;left:0;height:1px;background:#fff;}#forkongithub a::after{bottom:1px;top:auto;}@media screen and (min-width:800px){#forkongithub{z-index:10000;position:fixed;display:block;top:0;right:0;width:200px;overflow:hidden;height:200px;}#forkongithub a{width:200px;z-index:10000;position:fixed;top:25px;right:-60px;transform:rotate(45deg);-webkit-transform:rotate(45deg);box-shadow:4px 4px 10px rgba(0,0,0,0.8);}}</style><span id=\"forkongithub\"><a href=\"https://github.com/fresc81/node-winreg\">Fork me on GitHub</a></span>",
"copyright": "Copyright &copy; 2016 Paul Bottin.",
"navType": "vertical",
"linenums": true,
"theme": "cyborg"
} ,
"markdown": {
"parser": "gfm",
"hardwrap": true,
"githubRepoName": "node-winreg",
"githubRepoOwner": "fresc81"
}
}
+993
View File
@@ -0,0 +1,993 @@
/************************************************************************************************************
* registry.js - contains a wrapper for the REG command under Windows, which provides access to the registry
*
* @author Paul Bottin a/k/a FrEsC
*
*/
/* imports */
var util = require('util')
, path = require('path')
, spawn = require('child_process').spawn
/* set to console.log for debugging */
, log = function () {}
/* registry hive ids */
, HKLM = 'HKLM'
, HKCU = 'HKCU'
, HKCR = 'HKCR'
, HKU = 'HKU'
, HKCC = 'HKCC'
, HIVES = [ HKLM, HKCU, HKCR, HKU, HKCC ]
/* registry value type ids */
, REG_SZ = 'REG_SZ'
, REG_MULTI_SZ = 'REG_MULTI_SZ'
, REG_EXPAND_SZ = 'REG_EXPAND_SZ'
, REG_DWORD = 'REG_DWORD'
, REG_QWORD = 'REG_QWORD'
, REG_BINARY = 'REG_BINARY'
, REG_NONE = 'REG_NONE'
, REG_TYPES = [ REG_SZ, REG_MULTI_SZ, REG_EXPAND_SZ, REG_DWORD, REG_QWORD, REG_BINARY, REG_NONE ]
/* default registry value name */
, DEFAULT_VALUE = ''
/* general key pattern */
, KEY_PATTERN = /(\\[a-zA-Z0-9_\s]+)*/
/* key path pattern (as returned by REG-cli) */
, PATH_PATTERN = /^(HKEY_LOCAL_MACHINE|HKEY_CURRENT_USER|HKEY_CLASSES_ROOT|HKEY_USERS|HKEY_CURRENT_CONFIG)(.*)$/
/* registry item pattern */
, ITEM_PATTERN = /^(.*)\s(REG_SZ|REG_MULTI_SZ|REG_EXPAND_SZ|REG_DWORD|REG_QWORD|REG_BINARY|REG_NONE)\s+([^\s].*)$/
/**
* Creates an Error object that contains the exit code of the REG.EXE process.
* This contructor is private. Objects of this type are created internally and returned in the <code>err</code> parameters in case the REG.EXE process doesn't exit cleanly.
*
* @private
* @class
*
* @param {string} message - the error message
* @param {number} code - the process exit code
*
*/
function ProcessUncleanExitError(message, code) {
if (!(this instanceof ProcessUncleanExitError))
return new ProcessUncleanExitError(message, code);
Error.captureStackTrace(this, ProcessUncleanExitError);
/**
* The error name.
* @readonly
* @member {string} ProcessUncleanExitError#name
*/
this.__defineGetter__('name', function () { return ProcessUncleanExitError.name; });
/**
* The error message.
* @readonly
* @member {string} ProcessUncleanExitError#message
*/
this.__defineGetter__('message', function () { return message; });
/**
* The process exit code.
* @readonly
* @member {number} ProcessUncleanExitError#code
*/
this.__defineGetter__('code', function () { return code; });
}
util.inherits(ProcessUncleanExitError, Error);
/*
* Captures stdout/stderr for a child process
*/
function captureOutput(child) {
// Use a mutable data structure so we can append as we get new data and have
// the calling context see the new data
var output = {'stdout': '', 'stderr': ''};
child.stdout.on('data', function(data) { output["stdout"] += data.toString(); });
child.stderr.on('data', function(data) { output["stderr"] += data.toString(); });
return output;
}
/*
* Returns an error message containing the stdout/stderr of the child process
*/
function mkErrorMsg(registryCommand, code, output) {
var stdout = output['stdout'].trim();
var stderr = output['stderr'].trim();
var msg = util.format("%s command exited with code %d:\n%s\n%s", registryCommand, code, stdout, stderr);
return new ProcessUncleanExitError(msg, code);
}
/*
* Converts x86/x64 to 32/64
*/
function convertArchString(archString) {
if (archString == 'x64') {
return '64';
} else if (archString == 'x86') {
return '32';
} else {
throw new Error('illegal architecture: ' + archString + ' (use x86 or x64)');
}
}
/*
* Adds correct architecture to reg args
*/
function pushArch(args, arch) {
if (arch) {
args.push('/reg:' + convertArchString(arch));
}
}
/*
* Get the path to system's reg.exe. Useful when another reg.exe is added to the PATH
* Implemented only for Windows
*/
function getRegExePath() {
if (process.platform === 'win32') {
return path.join(process.env.windir, 'system32', 'reg.exe');
} else {
return "REG";
}
}
/**
* Creates a single registry value record.
* This contructor is private. Objects of this type are created internally and returned by methods of {@link Registry} objects.
*
* @private
* @class
*
* @param {string} host - the hostname
* @param {string} hive - the hive id
* @param {string} key - the registry key
* @param {string} name - the value name
* @param {string} type - the value type
* @param {string} value - the value
* @param {string} arch - the hive architecture ('x86' or 'x64')
*
*/
function RegistryItem (host, hive, key, name, type, value, arch) {
if (!(this instanceof RegistryItem))
return new RegistryItem(host, hive, key, name, type, value, arch);
/* private members */
var _host = host // hostname
, _hive = hive // registry hive
, _key = key // registry key
, _name = name // property name
, _type = type // property type
, _value = value // property value
, _arch = arch // hive architecture
/* getters/setters */
/**
* The hostname.
* @readonly
* @member {string} RegistryItem#host
*/
this.__defineGetter__('host', function () { return _host; });
/**
* The hive id.
* @readonly
* @member {string} RegistryItem#hive
*/
this.__defineGetter__('hive', function () { return _hive; });
/**
* The registry key.
* @readonly
* @member {string} RegistryItem#key
*/
this.__defineGetter__('key', function () { return _key; });
/**
* The value name.
* @readonly
* @member {string} RegistryItem#name
*/
this.__defineGetter__('name', function () { return _name; });
/**
* The value type.
* @readonly
* @member {string} RegistryItem#type
*/
this.__defineGetter__('type', function () { return _type; });
/**
* The value.
* @readonly
* @member {string} RegistryItem#value
*/
this.__defineGetter__('value', function () { return _value; });
/**
* The hive architecture.
* @readonly
* @member {string} RegistryItem#arch
*/
this.__defineGetter__('arch', function () { return _arch; });
}
util.inherits(RegistryItem, Object);
/**
* Creates a registry object, which provides access to a single registry key.
* Note: This class is returned by a call to ```require('winreg')```.
*
* @public
* @class
*
* @param {object} options - the options
* @param {string=} options.host - the hostname
* @param {string=} options.hive - the hive id
* @param {string=} options.key - the registry key
* @param {string=} options.arch - the optional registry hive architecture ('x86' or 'x64'; only valid on Windows 64 Bit Operating Systems)
*
* @example
* var Registry = require('winreg')
* , autoStartCurrentUser = new Registry({
* hive: Registry.HKCU,
* key: '\\Software\\Microsoft\\Windows\\CurrentVersion\\Run'
* });
*
*/
function Registry (options) {
if (!(this instanceof Registry))
return new Registry(options);
/* private members */
var _options = options || {}
, _host = '' + (_options.host || '') // hostname
, _hive = '' + (_options.hive || HKLM) // registry hive
, _key = '' + (_options.key || '') // registry key
, _arch = _options.arch || null // hive architecture
/* getters/setters */
/**
* The hostname.
* @readonly
* @member {string} Registry#host
*/
this.__defineGetter__('host', function () { return _host; });
/**
* The hive id.
* @readonly
* @member {string} Registry#hive
*/
this.__defineGetter__('hive', function () { return _hive; });
/**
* The registry key name.
* @readonly
* @member {string} Registry#key
*/
this.__defineGetter__('key', function () { return _key; });
/**
* The full path to the registry key.
* @readonly
* @member {string} Registry#path
*/
this.__defineGetter__('path', function () { return (_host.length == 0 ? '' : '\\\\' + _host + '\\') + _hive + _key; });
/**
* The registry hive architecture ('x86' or 'x64').
* @readonly
* @member {string} Registry#arch
*/
this.__defineGetter__('arch', function () { return _arch; });
/**
* Creates a new {@link Registry} instance that points to the parent registry key.
* @readonly
* @member {Registry} Registry#parent
*/
this.__defineGetter__('parent', function () {
var i = _key.lastIndexOf('\\')
return new Registry({
host: this.host,
hive: this.hive,
key: (i == -1)?'':_key.substring(0, i),
arch: this.arch
});
});
// validate options...
if (HIVES.indexOf(_hive) == -1)
throw new Error('illegal hive specified.');
if (!KEY_PATTERN.test(_key))
throw new Error('illegal key specified.');
if (_arch && _arch != 'x64' && _arch != 'x86')
throw new Error('illegal architecture specified (use x86 or x64)');
}
/**
* Registry hive key HKEY_LOCAL_MACHINE.
* Note: For writing to this hive your program has to run with admin privileges.
* @type {string}
*/
Registry.HKLM = HKLM;
/**
* Registry hive key HKEY_CURRENT_USER.
* @type {string}
*/
Registry.HKCU = HKCU;
/**
* Registry hive key HKEY_CLASSES_ROOT.
* Note: For writing to this hive your program has to run with admin privileges.
* @type {string}
*/
Registry.HKCR = HKCR;
/**
* Registry hive key HKEY_USERS.
* Note: For writing to this hive your program has to run with admin privileges.
* @type {string}
*/
Registry.HKU = HKU;
/**
* Registry hive key HKEY_CURRENT_CONFIG.
* Note: For writing to this hive your program has to run with admin privileges.
* @type {string}
*/
Registry.HKCC = HKCC;
/**
* Collection of available registry hive keys.
* @type {array}
*/
Registry.HIVES = HIVES;
/**
* Registry value type STRING.
* @type {string}
*/
Registry.REG_SZ = REG_SZ;
/**
* Registry value type MULTILINE_STRING.
* @type {string}
*/
Registry.REG_MULTI_SZ = REG_MULTI_SZ;
/**
* Registry value type EXPANDABLE_STRING.
* @type {string}
*/
Registry.REG_EXPAND_SZ = REG_EXPAND_SZ;
/**
* Registry value type DOUBLE_WORD.
* @type {string}
*/
Registry.REG_DWORD = REG_DWORD;
/**
* Registry value type QUAD_WORD.
* @type {string}
*/
Registry.REG_QWORD = REG_QWORD;
/**
* Registry value type BINARY.
* @type {string}
*/
Registry.REG_BINARY = REG_BINARY;
/**
* Registry value type UNKNOWN.
* @type {string}
*/
Registry.REG_NONE = REG_NONE;
/**
* Collection of available registry value types.
* @type {array}
*/
Registry.REG_TYPES = REG_TYPES;
/**
* The name of the default value. May be used instead of the empty string literal for better readability.
* @type {string}
*/
Registry.DEFAULT_VALUE = DEFAULT_VALUE;
/**
* Retrieve all values from this registry key.
* @param {valuesCallback} cb - callback function
* @param {ProcessUncleanExitError=} cb.err - error object or null if successful
* @param {array=} cb.items - an array of {@link RegistryItem} objects
* @returns {Registry} this registry key object
*/
Registry.prototype.values = function values (cb) {
if (typeof cb !== 'function')
throw new TypeError('must specify a callback');
var args = [ 'QUERY', this.path ];
pushArch(args, this.arch);
var proc = spawn(getRegExePath(), args, {
cwd: undefined,
env: process.env,
stdio: [ 'ignore', 'pipe', 'pipe' ]
})
, buffer = ''
, self = this
, error = null // null means no error previously reported.
var output = captureOutput(proc);
proc.on('close', function (code) {
if (error) {
return;
} else if (code !== 0) {
log('process exited with code ' + code);
cb(mkErrorMsg('QUERY', code, output), null);
} else {
var items = []
, result = []
, lines = buffer.split('\n')
, lineNumber = 0
for (var i = 0, l = lines.length; i < l; i++) {
var line = lines[i].trim();
if (line.length > 0) {
log(line);
if (lineNumber != 0) {
items.push(line);
}
++lineNumber;
}
}
for (var i = 0, l = items.length; i < l; i++) {
var match = ITEM_PATTERN.exec(items[i])
, name
, type
, value
if (match) {
name = match[1].trim();
type = match[2].trim();
value = match[3];
result.push(new RegistryItem(self.host, self.hive, self.key, name, type, value, self.arch));
}
}
cb(null, result);
}
});
proc.stdout.on('data', function (data) {
buffer += data.toString();
});
proc.on('error', function(err) {
error = err;
cb(err);
});
return this;
};
/**
* Retrieve all subkeys from this registry key.
* @param {function (err, items)} cb - callback function
* @param {ProcessUncleanExitError=} cb.err - error object or null if successful
* @param {array=} cb.items - an array of {@link Registry} objects
* @returns {Registry} this registry key object
*/
Registry.prototype.keys = function keys (cb) {
if (typeof cb !== 'function')
throw new TypeError('must specify a callback');
var args = [ 'QUERY', this.path ];
pushArch(args, this.arch);
var proc = spawn(getRegExePath(), args, {
cwd: undefined,
env: process.env,
stdio: [ 'ignore', 'pipe', 'pipe' ]
})
, buffer = ''
, self = this
, error = null // null means no error previously reported.
var output = captureOutput(proc);
proc.on('close', function (code) {
if (error) {
return;
} else if (code !== 0) {
log('process exited with code ' + code);
cb(mkErrorMsg('QUERY', code, output), null);
}
});
proc.stdout.on('data', function (data) {
buffer += data.toString();
});
proc.stdout.on('end', function () {
var items = []
, result = []
, lines = buffer.split('\n')
for (var i = 0, l = lines.length; i < l; i++) {
var line = lines[i].trim();
if (line.length > 0) {
log(line);
items.push(line);
}
}
for (var i = 0, l = items.length; i < l; i++) {
var match = PATH_PATTERN.exec(items[i])
, hive
, key
if (match) {
hive = match[1];
key = match[2];
if (key && (key !== self.key)) {
result.push(new Registry({
host: self.host,
hive: self.hive,
key: key,
arch: self.arch
}));
}
}
}
cb(null, result);
});
proc.on('error', function(err) {
error = err;
cb(err);
});
return this;
};
/**
* Gets a named value from this registry key.
* @param {string} name - the value name, use {@link Registry.DEFAULT_VALUE} or an empty string for the default value
* @param {function (err, item)} cb - callback function
* @param {ProcessUncleanExitError=} cb.err - error object or null if successful
* @param {RegistryItem=} cb.item - the retrieved registry item
* @returns {Registry} this registry key object
*/
Registry.prototype.get = function get (name, cb) {
if (typeof cb !== 'function')
throw new TypeError('must specify a callback');
var args = ['QUERY', this.path];
if (name == '')
args.push('/ve');
else
args = args.concat(['/v', name]);
pushArch(args, this.arch);
var proc = spawn(getRegExePath(), args, {
cwd: undefined,
env: process.env,
stdio: [ 'ignore', 'pipe', 'pipe' ]
})
, buffer = ''
, self = this
, error = null // null means no error previously reported.
var output = captureOutput(proc);
proc.on('close', function (code) {
if (error) {
return;
} else if (code !== 0) {
log('process exited with code ' + code);
cb(mkErrorMsg('QUERY', code, output), null);
} else {
var items = []
, result = null
, lines = buffer.split('\n')
, lineNumber = 0
for (var i = 0, l = lines.length; i < l; i++) {
var line = lines[i].trim();
if (line.length > 0) {
log(line);
if (lineNumber != 0) {
items.push(line);
}
++lineNumber;
}
}
//Get last item - so it works in XP where REG QUERY returns with a header
var item = items[items.length-1] || ''
, match = ITEM_PATTERN.exec(item)
, name
, type
, value
if (match) {
name = match[1].trim();
type = match[2].trim();
value = match[3];
result = new RegistryItem(self.host, self.hive, self.key, name, type, value, self.arch);
}
cb(null, result);
}
});
proc.stdout.on('data', function (data) {
buffer += data.toString();
});
proc.on('error', function(err) {
error = err;
cb(err);
});
return this;
};
/**
* Sets a named value in this registry key, overwriting an already existing value.
* @param {string} name - the value name, use {@link Registry.DEFAULT_VALUE} or an empty string for the default value
* @param {string} type - the value type
* @param {string} value - the value
* @param {function (err)} cb - callback function
* @param {ProcessUncleanExitError=} cb.err - error object or null if successful
* @returns {Registry} this registry key object
*/
Registry.prototype.set = function set (name, type, value, cb) {
if (typeof cb !== 'function')
throw new TypeError('must specify a callback');
if (REG_TYPES.indexOf(type) == -1)
throw Error('illegal type specified.');
var args = ['ADD', this.path];
if (name == '')
args.push('/ve');
else
args = args.concat(['/v', name]);
args = args.concat(['/t', type, '/d', value, '/f']);
pushArch(args, this.arch);
var proc = spawn(getRegExePath(), args, {
cwd: undefined,
env: process.env,
stdio: [ 'ignore', 'pipe', 'pipe' ]
})
, error = null // null means no error previously reported.
var output = captureOutput(proc);
proc.on('close', function (code) {
if(error) {
return;
} else if (code !== 0) {
log('process exited with code ' + code);
cb(mkErrorMsg('ADD', code, output, null));
} else {
cb(null);
}
});
proc.stdout.on('data', function (data) {
// simply discard output
log(''+data);
});
proc.on('error', function(err) {
error = err;
cb(err);
});
return this;
};
/**
* Remove a named value from this registry key. If name is empty, sets the default value of this key.
* Note: This key must be already existing.
* @param {string} name - the value name, use {@link Registry.DEFAULT_VALUE} or an empty string for the default value
* @param {function (err)} cb - callback function
* @param {ProcessUncleanExitError=} cb.err - error object or null if successful
* @returns {Registry} this registry key object
*/
Registry.prototype.remove = function remove (name, cb) {
if (typeof cb !== 'function')
throw new TypeError('must specify a callback');
var args = name ? ['DELETE', this.path, '/f', '/v', name] : ['DELETE', this.path, '/f', '/ve'];
pushArch(args, this.arch);
var proc = spawn(getRegExePath(), args, {
cwd: undefined,
env: process.env,
stdio: [ 'ignore', 'pipe', 'pipe' ]
})
, error = null // null means no error previously reported.
var output = captureOutput(proc);
proc.on('close', function (code) {
if(error) {
return;
} else if (code !== 0) {
log('process exited with code ' + code);
cb(mkErrorMsg('DELETE', code, output), null);
} else {
cb(null);
}
});
proc.stdout.on('data', function (data) {
// simply discard output
log(''+data);
});
proc.on('error', function(err) {
error = err;
cb(err);
});
return this;
};
/**
* Remove all subkeys and values (including the default value) from this registry key.
* @param {function (err)} cb - callback function
* @param {ProcessUncleanExitError=} cb.err - error object or null if successful
* @returns {Registry} this registry key object
*/
Registry.prototype.clear = function clear (cb) {
if (typeof cb !== 'function')
throw new TypeError('must specify a callback');
var args = ['DELETE', this.path, '/f', '/va'];
pushArch(args, this.arch);
var proc = spawn(getRegExePath(), args, {
cwd: undefined,
env: process.env,
stdio: [ 'ignore', 'pipe', 'pipe' ]
})
, error = null // null means no error previously reported.
var output = captureOutput(proc);
proc.on('close', function (code) {
if(error) {
return;
} else if (code !== 0) {
log('process exited with code ' + code);
cb(mkErrorMsg("DELETE", code, output), null);
} else {
cb(null);
}
});
proc.stdout.on('data', function (data) {
// simply discard output
log(''+data);
});
proc.on('error', function(err) {
error = err;
cb(err);
});
return this;
};
/**
* Alias for the clear method to keep it backward compatible.
* @method
* @deprecated Use {@link Registry#clear} or {@link Registry#destroy} in favour of this method.
* @param {function (err)} cb - callback function
* @param {ProcessUncleanExitError=} cb.err - error object or null if successful
* @returns {Registry} this registry key object
*/
Registry.prototype.erase = Registry.prototype.clear;
/**
* Delete this key and all subkeys from the registry.
* @param {function (err)} cb - callback function
* @param {ProcessUncleanExitError=} cb.err - error object or null if successful
* @returns {Registry} this registry key object
*/
Registry.prototype.destroy = function destroy (cb) {
if (typeof cb !== 'function')
throw new TypeError('must specify a callback');
var args = ['DELETE', this.path, '/f'];
pushArch(args, this.arch);
var proc = spawn(getRegExePath(), args, {
cwd: undefined,
env: process.env,
stdio: [ 'ignore', 'pipe', 'pipe' ]
})
, error = null // null means no error previously reported.
var output = captureOutput(proc);
proc.on('close', function (code) {
if (error) {
return;
} else if (code !== 0) {
log('process exited with code ' + code);
cb(mkErrorMsg('DELETE', code, output), null);
} else {
cb(null);
}
});
proc.stdout.on('data', function (data) {
// simply discard output
log(''+data);
});
proc.on('error', function(err) {
error = err;
cb(err);
});
return this;
};
/**
* Create this registry key. Note that this is a no-op if the key already exists.
* @param {function (err)} cb - callback function
* @param {ProcessUncleanExitError=} cb.err - error object or null if successful
* @returns {Registry} this registry key object
*/
Registry.prototype.create = function create (cb) {
if (typeof cb !== 'function')
throw new TypeError('must specify a callback');
var args = ['ADD', this.path, '/f'];
pushArch(args, this.arch);
var proc = spawn(getRegExePath(), args, {
cwd: undefined,
env: process.env,
stdio: [ 'ignore', 'pipe', 'pipe' ]
})
, error = null // null means no error previously reported.
var output = captureOutput(proc);
proc.on('close', function (code) {
if (error) {
return;
} else if (code !== 0) {
log('process exited with code ' + code);
cb(mkErrorMsg('ADD', code, output), null);
} else {
cb(null);
}
});
proc.stdout.on('data', function (data) {
// simply discard output
log(''+data);
});
proc.on('error', function(err) {
error = err;
cb(err);
});
return this;
};
/**
* Checks if this key already exists.
* @param {function (err, exists)} cb - callback function
* @param {ProcessUncleanExitError=} cb.err - error object or null if successful
* @param {boolean=} cb.exists - true if a registry key with this name already exists
* @returns {Registry} this registry key object
*/
Registry.prototype.keyExists = function keyExists (cb) {
this.values(function (err, items) {
if (err) {
// process should return with code 1 if key not found
if (err.code == 1) {
return cb(null, false);
}
// other error
return cb(err);
}
cb(null, true);
});
return this;
};
/**
* Checks if a value with the given name already exists within this key.
* @param {string} name - the value name, use {@link Registry.DEFAULT_VALUE} or an empty string for the default value
* @param {function (err, exists)} cb - callback function
* @param {ProcessUncleanExitError=} cb.err - error object or null if successful
* @param {boolean=} cb.exists - true if a value with the given name was found in this key
* @returns {Registry} this registry key object
*/
Registry.prototype.valueExists = function valueExists (name, cb) {
this.get(name, function (err, item) {
if (err) {
// process should return with code 1 if value not found
if (err.code == 1) {
return cb(null, false);
}
// other error
return cb(err);
}
cb(null, true);
});
return this;
};
module.exports = Registry;
+32
View File
@@ -0,0 +1,32 @@
{
"name": "winreg",
"version": "1.2.4",
"description": "provides access to the windows registry through the REG tool",
"main": "lib/registry.js",
"scripts": {
"test": "mocha test",
"generate-docs": "jsdoc -c ./jsdoc.conf.json",
"download-docs": "git clone -b gh-pages https://github.com/fresc81/node-winreg.git docs",
"checkout-docs": "git clone -b gh-pages git@github.com:fresc81/node-winreg.git docs"
},
"homepage": "http://fresc81.github.io/node-winreg",
"repository": {
"type": "git",
"url": "git://github.com/fresc81/node-winreg.git"
},
"keywords": [
"windows",
"registry"
],
"author": "Paul Bottin",
"license": "BSD-2-Clause",
"readmeFilename": "README.md",
"gitHead": "36cfe63a8dcb700cf44b0b7317827099d19c26c1",
"devDependencies": {
"ink-docstrap": "^1.1.4",
"jsdoc": "^3.4.0",
"mocha": "^3.0.2",
"moment": "^2.11.2",
"unit.js": "^2.0.0"
}
}
+5
View File
@@ -0,0 +1,5 @@
--reporter spec
--recursive
--timeout 3000
--slow 500
--growl
+381
View File
@@ -0,0 +1,381 @@
// this should reveal wrong iteration on arrays
Array.prototype.someNewMethod = function() {};
var test = require('unit.js');
describe('winreg', function(){
it('running on Windows', function () {
test.string(process.platform)
. is('win32');
});
// Registry class
var Registry = require(__dirname+'/../../lib/registry.js');
it('Registry is a class', function () {
test.function(Registry)
. hasName('Registry');
});
// create a uniqe registry key in HKCU to test in
var regKey = new Registry({
hive: Registry.HKCU,
key: '\\Software\\AAA_' + new Date().toISOString()
});
it('regKey is instance of Registry', function(){
test.object(regKey)
. isInstanceOf(Registry);
});
// a key that has subkeys in it
var softwareKey = new Registry({
hive: Registry.HKCU,
key: '\\Software'
});
it('softwareKey is instance of Registry', function(){
test.object(softwareKey)
. isInstanceOf(Registry);
});
it('can change the prototype', function (done) {
var magicString = new Date().toISOString();
Registry.prototype.toString = function () {
return magicString;
};
var instance = new Registry({
hive: Registry.HKCU,
key: '\\Software'
});
test.string(instance.toString())
. is(magicString);
done();
});
describe('Registry', function (){
describe('keyExists()', function(){
it('regKey has keyExists method', function () {
test.object(regKey)
. hasProperty('keyExists');
test.function(regKey.keyExists)
. hasName('keyExists');
});
it('regKey does not already exist', function(done) {
regKey.keyExists(function (err, exists) {
if (err) throw err;
test.bool(exists)
. isNotTrue();
done();
});
});
}); // end - describe keyExists()
describe('create()', function(){
it('regKey has create method', function () {
test.object(regKey)
. hasProperty('create');
test.function(regKey.create)
. hasName('create');
});
it('regKey can be created', function(done) {
regKey.create(function (err) {
if (err) throw err;
done();
});
});
it('regKey exists after being created', function(done) {
regKey.keyExists(function (err, exists) {
if (err) throw err;
test.bool(exists)
. isTrue();
done();
});
});
}); // end - describe create()
describe('set()', function (){
it('regKey has set method', function () {
test.object(regKey)
. hasProperty('set');
test.function(regKey.set)
. hasName('set');
});
it('can set a string value', function (done) {
regKey.set('SomeString', Registry.REG_SZ, 'SomeValue', function (err) {
if (err) throw err;
done();
});
});
}); // end - describe set
describe('valueExists()', function (){
it('regKey has valueExists method', function () {
test.object(regKey)
. hasProperty('valueExists');
test.function(regKey.valueExists)
. hasName('valueExists');
});
it('can check for existing string value', function (done) {
regKey.valueExists('SomeString', function (err, exists) {
if (err) throw err;
test.bool(exists)
. isTrue();
done();
});
});
}); // end - describe valueExists
describe('get()', function (){
it('regKey has get method', function () {
test.object(regKey)
. hasProperty('get');
test.function(regKey.get)
. hasName('get');
});
it('can get a string value', function (done) {
regKey.get('SomeString', function (err, item) {
if (err) throw err;
test.object(item)
. hasProperty('value', 'SomeValue');
done();
});
});
}); // end - describe get
describe('values()', function (){
it('regKey has values method', function () {
test.object(regKey)
. hasProperty('values');
test.function(regKey.values)
. hasName('values');
});
it('returns array of RegistryItem objects', function (done) {
regKey.values(function (err, items) {
if (err) throw err;
for (var i=0; i<items.length; i++) {
var item = items[i];
test.object(item)
. hasProperty('value');
}
done();
});
});
}); // end - describe values
describe('remove()', function (){
it('regKey has remove method', function () {
test.object(regKey)
. hasProperty('remove');
test.function(regKey.remove)
. hasName('remove');
});
it('can remove a string value', function (done) {
regKey.remove('SomeString', function (err) {
if (err) throw err;
done();
});
});
}); // end - describe remove
describe('keys()', function (){
it('regKey has keys method', function () {
test.object(regKey)
. hasProperty('keys');
test.function(regKey.keys)
. hasName('keys');
});
it('returns array of Registry objects', function (done) {
softwareKey.keys(function (err, keys) {
if (err) throw err;
test.array(keys);
for (var i=0; i<keys.length; i++) {
var key = keys[i];
test.object(key)
. isInstanceOf(Registry);
}
done();
});
});
}); // end - describe keys()
describe('clear()', function (){
it('regKey has clear method', function () {
test.object(regKey)
. hasProperty('clear');
test.function(regKey.clear)
. hasName('clear');
});
}); // end - describe clear
describe('destroy()', function(){
it('regKey has destroy method', function () {
test.object(regKey)
. hasProperty('destroy');
test.function(regKey.destroy)
. hasName('destroy');
});
it('regKey can be destroyed', function(done) {
regKey.destroy(function (err) {
if (err) throw err;
done();
});
});
it('regKey is missing after being destroyed', function(done) {
regKey.keyExists(function (err, exists) {
if (err) throw err;
test.bool(exists)
. isFalse();
done();
});
});
}); // end - describe destroy()
}); // end - describe Registry
}); // end - describe winreg