0.5.4 • Published 4 years ago

@js.properties/properties v0.5.4

Weekly downloads
7,237
License
MIT
Repository
github
Last release
4 years ago

@js.properties/properties

JavaScript .properties parser & stringifier

Build Status npm license

This is a parser and stringifier written in JavaScript and PEG.js for Java .properties file format, following the syntax defined in Java API Specification.

The parser can return parsed properties object (parse or parseToProperites) in a flat structure or a hierarchical namespaced structure, or return raw parsing result (parseToEntries) as an array of entry objects which have key, element, sep, indent, eol, original and location as keys.

As to the raw parsing result:

  • Each logical line of input .properties file is parsed into an object, with the original logical line, indent key sep element eol parts, and/or line location info optionally kept;
  • Properties with duplicate keys are kept in the raw output so that one can build high-level applications reporting them;
  • Blank and comment lines can be kept as well so that there is no info loss of the original file after parsing. This could be useful for something like .properties IDE.

The stingifier (stringify, stringifyFromProperties or stringifyFromEntries) effectively does the reverse of what the parser does.

Installation

npm install --save @js.properties/properties
# or
yarn add @js.properties/properties

Quick Example

example.properties:

# Comment here
hello = world

  foo : bar

demo.js (Node.js):

const fs = require('fs');
const Properties = require('@js.properties/properties');

const input = fs.readFileSync('example.properties', 'utf8');
const options = {   // options is optional
  all: true,        // Include empty and blank lines
  sep: true,        // Include separator in output
  indent: true,     // Include indentation in output
  eol: true,        // Include eol (end of line) in output
  original: true,   // Include original logical line in output
  location: true,   // Include location info in output
};
let output = Properties.parseToEntries(input, options);

demo.html (Browser):

<!-- @js.properties/properties is available as an UMD module. -->
<script src="properties.min.js"></script>
<script>
// Input can be entered manually or read via FileReader API
var output = Properties.parseToEntries('...');
</script>

Output with all options off:

[
  { "key": "hello", "element": "world" },
  { "key": "foo", "element": "bar" }
]

Output with all options on:

[
  {
    "key": null, "element": null,
    "sep": null, "indent": "", "eol": "\n",
    "original": "# Comment here",
    "location": {
      "start": { "offset":  0, "line": 1, "column":  1 },
      "end":   { "offset": 14, "line": 1, "column": 15 } }
  },
  {
    "key": "hello", "element": "world",
    "sep": " = ", "indent": "", "eol": "\n",
    "original": "hello = world",
    "location": {
      "start": { "offset": 15, "line": 2, "column":  1 },
      "end":   { "offset": 28, "line": 2, "column": 14 } }
  },
  {
    "key": null, "element": null,
    "sep": null, "indent": "", "eol": "\n",
    "original": "",
    "location": {
      "start": { "offset": 29, "line": 3, "column":  1 },
      "end":   { "offset": 29, "line": 3, "column":  1 } }
  },
  {
    "key": "foo", "element": "bar",
    "sep": " : ", "indent": "  ", "eol": "\n",
    "original": "  foo : bar",
    "location": {
      "start": { "offset": 30, "line": 4, "column":  1 },
      "end":   { "offset": 41, "line": 4, "column": 12 } }
  }
]

There is also a method parseToProperties(input) (alias parse) which generates output like:

{
  "hello": "world",
  "foo": "bar"
}

API

Method: parseToProperties(string , options )

Method Alias: parse(string , options )

Object: options

OptionTypeDescription
namespacebooleanParse dot separated keys as namespaced

All options default to false.

true and { '': true } can be used as a shortcut to turn on all options. { '': true, namespace: false } can be used to turn on all options except for those listed explicitly.

Returns: object

Throws: SyntaxError Invalid Unicode escape sequence

Method: parseToEntries(string , options )

Object: options

OptionTypeDescription
allbooleanInclude empty and blank lines
sepbooleanInclude separator in output
indentbooleanInclude indentation in output
eolbooleanInclude eol (end of line) in output
originalbooleanInclude original logical line in output
locationbooleanInclude location info in output

All options default to false.

true and { '': true } can be used as a shortcut to turn on all options. { '': true, location: false } can be used to turn on all options except for those listed explicitly.

Returns: Array<PropertyEntry>

Object: PropertyEntry

PropertyTypeDescription
keystring | nullProperty Key
elementstring | nullProperty Element (value)
sepstring | null(optional) The separator of the property
indentstring(optional) The indentation of the property
eolstring | null(optional) The eol (end of line) of the logical line *
originalstring(optional) The original logical line * containing the property
locationLocation(optional) The start and end position of the logical line *

Note: key, element and sep will be null for blank and comment lines.

Note: indent is always a string, in the case of no indentation, it's an empty string.

Note: original is always a string, in the case of blank line, it's an empty string.

Note: eol will be null if this is the last line and contains no final eol.

* A logical line may spread across several natural lines if line continuation is involved.

Object: Location

{ start: Position, end: Position }

Object: Position

{ offset: number, line: number, column: number }

Method: stringifyFromProperties(object , options )

Turn properties object into .properties file string.

Method: stringifyFromEntries(Array\ , options )

When stringifying from entries, if original is set in the entry, it's used; otherwise, property is computed from key, sep and element.

Method: stringify(object | Array\ , options )

This is an alias for stringifyFromProperties and stringifyFromEntries depending on the type of arguments.

Object: stringify options

OptionTypeDefaultDescription
sepstring" = "The separator to use *
eolstring"\r\n"The eol (end of line) to use *
namespacestring""A namespace to prefix all keys **

* Thses options are used in stringify, stringifyFromProperties and stringifyFromEntries. In the case of stringifying from entries, option values are considered only if relevant field does not exist in the entry.

** Used only in stringify or stringifyFromProperties.


Development

Code Structure

@js.properties/properties
├── src            // Originally authored source code.
│   └── *.pegjs.js //   This one is an exception, generated by pegjs.
├── types          // TypeScript declaration files
├── cjs            // Generated by babel, spread in multiple files,
│                  //   in CommonJS format, for Node.js use.
├── umd            // Generated by webpack into a single file,
│                  //   in UMD format, for browser and Node.js.
└── test
    ├── data       // Test data, *.properties are authored
    │              //   and *.json are generated and compared
    ├── java       // Reference implementation in Java
    └── js         // Test code in JavaScript

Build

yarn run prepare
# or
npm run prepare

Test & Lint

yarn test
# or
npm test

Test Only

yarn tap
# or
npm tap

Update expected test output

yarn run tap:snapshot
# or
npm run tap:snapshot

Lint Only

yarn run lint
# or
npm run lint

LICENSE

The MIT License. See LICENSE file.