Skip to content
Browse files

testing

  • Loading branch information...
1 parent 76a0f48 commit dd474a11f62bfc269e7a443f4288d8dcff127ef3 Frank Hellwig committed Sep 25, 2012
Showing with 77 additions and 95 deletions.
  1. +18 −4 README.md
  2. +56 −91 pkgconfig.js
  3. +3 −0 test.js
View
22 README.md
@@ -4,12 +4,16 @@ Reads and validates JSON configuration files for Node.js packages.
## Overview
-Applications often get their settings from configuration files. These files are usually structured as JSON text or JavaScript objects. Reading these files is easily accomplished. However, validating that the values are of the correct type or fall within an appropriate range should *not* be performed by application code. Reading configuration files and validating them against a JSON schema is the object of the pkgconfig utility.
+Applications often get their settings from configuration files. These files are usually structured as JSON text or JavaScript objects. Reading these files is easily accomplished. However, validating that the values are of the correct type or fall within an appropriate range should not be performed by application code. Reading configuration files and validating them against a JSON schema is the object of the pkgconfig utility.
This package uses the [findpkg](https://github.com/fhellwig/findpkg) utility for finding the top-level package directory of the module requiring pkgconfig. It then looks for a `config` directory in this top-level directory. The `config` directory must contain a configuration file and a schema file. The configuration file is read and validated against the schema file using the [JSV](https://github.com/garycourt/JSV) implementation.
## Installation
+This section describes the installation of pkgconfig and the default directory layout.
+
+### Dependencies
+
Add pkgconfig to your `package.json` depencencies and run `npm install`.
"dependencies": {
@@ -19,6 +23,8 @@ Add pkgconfig to your `package.json` depencencies and run `npm install`.
$ npm install
+### Layout
+
Create a `config` directory in the top-level directory of your Node.js application. Add a `schema.json` and a `config.json` file to this directory.
myapp/
@@ -30,7 +36,11 @@ Create a `config` directory in the top-level directory of your Node.js applicati
## Usage
-Require pkgconfig and call the function.
+This section describes the pkgconfig function, the default values, the options object, and environment variables.
+
+### Function
+
+Require pkgconfig and call the function returned from `require('pkgconfig')`.
```javascript
var pkgconfig = require('pkgconfig');
@@ -39,13 +49,15 @@ var config = pkgconfig();
This reads the `config.json` configuration file and validates it against the `schema.json` schema file.
-### Options
+### Defaults
Be default, pkgconfig looks for the following schema and a configuration files:
- `<your-package-base>/config/schema.(js|json)`
- `<your-package-base>/config/config.(js|json)`
+### Options
+
These defaults can be changed by passing an options object to the `pkgconfig` function.
```javascript
@@ -59,7 +71,9 @@ var options = {
var config = pkgconfig(options);
```
-Either property can be a JavaScript object or the pathname to a file (with or without an extension). If it is a pathname, then it is resolved against the requiring package's base directory unless the pathname begins with a dot (i.e., `./` or `../`) in which case it is resolved against the current working directory.
+Either one of these properties can be a JavaScript object or the pathname to a file (with or without an extension). If an options property is not specified, it falls back to the default value.
+
+If it is a pathname, then it is resolved against the requiring package's base directory unless the pathname begins with a dot (i.e., `./` or `../`) in which case it is resolved against the current working directory.
### Environment
View
147 pkgconfig.js
@@ -28,129 +28,94 @@ var strformat = require('strformat');
var DEFAULT_SCHEMA = path.join('config', 'schema');
var DEFAULT_CONFIG = path.join('config', 'config');
+
var PKGCONFIG_FILE = process.env['PKGCONFIG_FILE'];
+var OPTIONS_SCHEMA = {
+ type: 'object',
+ properties: {
+ schema: {
+ type: ['object', 'string'],
+ default: DEFAULT_SCHEMA
+ },
+ config: {
+ type: ['object', 'string'],
+ default: DEFAULT_CONFIG
+ }
+ }
+};
+
/**
- * Returns true if the pathname exists and is a file.
+ * Returns true if the pathname identifies a file.
*/
function isFile(pathname) {
return fs.existsSync(pathname) && fs.statSync(pathname).isFile();
}
/**
- * Reads the file as either a JavaScript module or a JSON file.
- * Returns a JavaScript object or null if the file is not found.
+ * Reads and parses JSON file. If a syntax error occurs, the pathname is
+ * included in the error message.
+ */
+function readJsonFile(pathname) {
+ var json = fs.readFileSync(pathname, 'utf8');
+ try {
+ return JSON.parse(json);
+ } catch (err) {
+ if (err instanceof SyntaxError) {
+ err.message = strformat("{0} in '{1}'", err.message, pathname);
+ }
+ throw err;
+ }
+}
+
+/**
+ * Reads the file specified by the pathname. If the file does not exist,
+ * then .js and .json extensions are added. Returns a JavaScript object.
+ * Throws an error if the file is not found.
*/
function readFile(pathname) {
+ var msg = ''; // additional error message info
var ext = path.extname(pathname).toLowerCase();
if (ext === '.js') {
if (isFile(pathname)) {
return require(pathname);
- } else {
- return null;
}
- }
- if (ext === '.json') {
+ } else if (ext === '.json') {
if (isFile(pathname)) {
- var text = fs.readFileSync(pathname, 'utf8');
- try {
- return JSON.parse(text);
- } catch (err) {
- if (err instanceof SyntaxError) {
- err.message = err.message + ' in ' + pathname;
- }
- throw err;
- }
- } else {
- return null;
+ return readJsonFile(pathname);
}
- }
- if (ext === '') {
- return readFile(pathname + '.js') || readFile(pathname + '.json');
- }
- throw new Error(strformat("Invalid file extension '{0}' in '{1}' (expected .js or .json)", ext, pathname));
-}
-
-/**
- * Removes any .js or .json extension from the specified pathname.
- */
-function removeExtension(pathname) {
- var ext = path.extname(pathname);
- var extlc = ext.toLowerCase();
- if (extlc === '.js' || extlc === '.json') {
- return path.basename(pathname, ext);
} else {
- return pathname;
+ if (isFile(pathname + '.js')) {
+ return require(pathname + '.js');
+ } else if (isFile(pathname + '.json')) {
+ return readJsonFile(pathname + '.json');
+ } else {
+ msg = ' (tried .js and .json)'; // note leading space
+ }
}
+ throw new Error(strformat("File not found '{0}'{1}", pathname, msg));
}
/**
- * Processes the options argument passed to the pkgconfig function.
- * Returns an options object with the default values applied.
+ * The function exported by this module.
*/
-function processOptions(options) {
+function pkgconfig(options) {
if (typeof options === 'undefined') {
options = {};
}
- options = jsvutil.validate(options, {
- type: 'object',
- properties: {
- schema: {
- type: ['object', 'string'],
- default: DEFAULT_SCHEMA
- },
- config: {
- type: ['object', 'string'],
- default: DEFAULT_CONFIG
- }
- }
- });
+ options = jsvutil.validate(options, OPTIONS_SCHEMA);
if (PKGCONFIG_FILE) {
options.config = PKGCONFIG_FILE;
}
-}
-
-/**
- * Processes the schema option.
- */
-function getSchema(base, option) {
- if (typeof option === 'object') {
- return option;
- }
- var pathname = removeExtension(path.resolve(base, option));
- var schema = readFile(pathname);
- if (schema === null) {
- throw new Error('Schema file not found: ' + pathname + '.(js|json)');
- }
- return schema;
-}
-
-/**
- * Processes the config option.
- */
-function getConfig(base, option) {
- if (typeof option === 'object') {
- return option;
+ var pkginfo = findpkg(module.parent);
+ if (typeof options.schema === 'string') {
+ options.schema = readFile(pkginfo.resolve(options.schema));
}
- var pathname = removeExtension(path.resolve(base, option));
- var config = readFile(pathname);
- if (config === null) {
- throw new Error('Config file not found: ' + pathname + '.(js|json)');
+ if (typeof options.config === 'string') {
+ options.config = readFile(pkginfo.resolve(options.config));
}
- return config;
-}
-
-/**
- * The function exported by this module.
- */
-function pkgconfig(options) {
- var pkginfo = findpkg(module.parent);
- var base = pkginfo.dirname;
- var options = processOptions(options);
- var schema = getSchema(base, options.schema);
- var config = getConfig(base, options.config);
- jsvutil.check(schema);
- jsvutil.validate(schema, config);
+ jsvutil.check(options.schema);
+ jsvutil.validate(options.schema, options.config);
return config;
}
View
3 test.js
@@ -0,0 +1,3 @@
+var pkgconfig = require('./pkgconfig');
+
+var config = pkgconfig({schema: 'config/schema.js'});

0 comments on commit dd474a1

Please sign in to comment.
Something went wrong with that request. Please try again.