.properties file parser, JSON converter and Webpack loader.

Overview

properties-file

License npm download Coverage Dependencies Known Vulnerabilities

.properties file parser, JSON converter and Webpack loader.

Installation 💻

in June 2022 we have released version 2 of this package which is not compatible with the previous versions. Make sure to read the documentation before upgrading.

Add the package as a dependency:

npm install properties-file

What's in it for me? 🤔

  • A modern TypeScript library that reproduces exactly the Properties Java implementation.
  • Flexible APIs:
    • propertiesToJson allows quick conversion from .properties files to JSON.
    • getProperties returns a Properties object that allows insights into parsing issues such as key collisions.
    • propertiesToJson & getProperties also have a browser-compatible version when passing directly the content of a file using the APIs under properties-file/content.
    • Out of the box Webpack loader to import .properties files directly in your application.
  • 100% test coverage based on the output from a Java implementation.
  • Active maintenance (many popular .properties packages have been inactive years).

Usage 🎬

We put a lot of effort into adding TSDoc to all our APIs. Please check directly in your IDE if you are unsure how to use certain APIs provided in our examples.

Both APIs (getProperties and propertiesToJson) directly under properties-file depend on fs which means they cannot be used by browsers. If you cannot use fs and already have a .properties file content, the same APIs are available under properties-file/content. Instead of taking the filePath as the first argument, they take content. The example below will use "fs" APIs since they are the most common use cases.

propertiesToJson

This API is probably the most used. You have a .properties file that you want to open and access like a simple key/value JSON object. Here is how this can be done with a single API call:

import { propertiesToJson } from 'properties-file';

console.log(propertiesToJson('hello-world.properties'));

Output:

{ hello: 'hello', world: 'world' }

If you cannot use fs and already have the content of a .properties file, your code would look like this instead:

import { propertiesToJson } from 'properties-file/content';

// ...some code to get the .properties file content into a variable called `propertiesFileContent`

console.log(propertiesToJson(propertiesFileContent));

getProperties (advanced use case)

Java's implementation of Properties is quite resilient. In fact, there are only two ways an exception can be thrown:

  • The file is not found.
  • A (\u) Unicode escape character is malformed.

This means that almost all files will be valid.

But what about a file that has duplicate keys? Duplicate keys have no reason to exist and they probably should have thrown errors as well but instead Java decided to simply overwrite the value with the latest occurrence in a file.

So how can we know if there were duplicate keys if we want to log some warnings? Simply by using getProperties which will return all the data that was used to parse the content. Here is an example on how it can be used:

# collisions-test.properties
hello: hello1
world: world1
world: world2
hello: hello2
world: world3
import { getProperties } from 'properties-file';

const properties = getProperties('assets/tests/collisions-test.properties');

properties.collection.forEach((property) => {
  console.log(`${property.key} => '${property.value}'`);
});

/**
 * Outputs:
 *
 * hello => 'hello2'
 * world => 'world3'
 *
 */

const keyCollisions = properties.getKeyCollisions();

keyCollisions.forEach((keyCollision) => {
  console.warn(
    `Found a key collision for key '${
      keyCollision.key
    }' on lines ${keyCollision.startingLineNumbers.join(
      ', '
    )} (will use the value at line ${keyCollision.getApplicableLineNumber()}).`
  );
});

/**
 * Outputs:
 *
 * Found a key collision for key 'hello' on lines 1, 4 (will use the value at line 4).
 * Found a key collision for key 'world' on lines 2, 3, 5 (will use the value at line 5).
 *
 */

Webpack File Loader

If you would like to import .properties directly using import, this package comes with its own Webpack file loader located under properties-file/webpack-loader. Here is an example of how to configure it:

// webpack.config.js
module.exports = {
  module: {
    rules: [
      {
        test: /\.properties$/i,
        use: [
          {
            loader: 'properties-file/webpack-loader',
          },
        ],
      },
    ],
  },
};

As soon as you configure Webpack, the .properties type should be available in your IDE when using import. If you ever need to add it manually, you can add a *.properties type declaration file at the root of your application, like this:

// properties-file.d.ts
declare module '*.properties' {
  const properties: { readonly [key: string]: string };
  export default properties;
}

By adding these configurations you should now be able to import directly .properties files just like this:

import helloWorld from './hello-world.properties';

console.dir(helloWorld);

Output:

{ "hello": "world" }

Why another .properties file package?

There are probably over 20 similar packages available but:

  • A lot of the most popular packages have had no activity for over 5 years.
  • A large portion of the packages will not replicate the current Java implementation.
  • No package offers the same capabilities as this one.

Unfortunately the .properties file specification is not well documented. One reason for this is that it was originally used in Java to store configurations. Most applications will handle this using JSON, YAML or other modern formats today because the formats are more flexible.

So why .properties files?

While many options exists today to handle configurations, .properties file remain one of the best option to store localizable strings (also known as messages). On the Java side, PropertyResourceBundle is how most implementations handle localization today. Because of its simplicity and maturity, .properties files remain one of the best options today when it comes to internationalization (i18n):

File format Key/value based Supports inline comments Built for localization Good linguistic tools support
.properties Yes Yes Yes (Resource Bundles) Yes
JSON No (can do more) No (requires JSON5) No Depends on the schema
YAML No (can do more) Yes No Depends on the schema

By having good JavaScript/TypeScript support for .properties files, it provides more options when it comes to i18n.

How does this package work?

Basically our goal was to offer parity with the Java implementation, which is the closest thing to a specification .properties file have. Here is in a nutshell the logic behind this package:

  1. Split the file content by lines (create line objects)
  2. Create LineObjects by combining multi-line properties and removing trailing backslash
  3. Create PropertyObjects from LineObjects that combined all lines of a property
  4. Identify the key/value delimiter and populate escaped keys and values.
  5. Unescape keys and values
  6. Create a PropertiesObject that will include all PropertyObjects while removing collisions

Just like Java, if a Unicode escaped characters (\u) is malformed, it will throw an error. But of course, we do not recommend using Unicode escaped characters but rather UTF-8 encoding that supports more characters.

Additional references

Special mention

Thanks to @calibr, the creator of properties-file version 1.0, for letting us use the https://www.npmjs.com/package/properties-file package name. We hope that it will make it easier to find our package.

You might also like...

React/Express/Webpack Boilerplate

React Boilerplate The following repo contains a very basic setup git clone https://github.com/asieke/React-Express-Boilerplate.git cd React-Express-Bo

Dec 30, 2022

Webpack plugin that helps importing .cdc files

Webpack plugin that helps importing .cdc files

cadence-webpack-plugin Webpack plugin that helps importing .cdc files and polyfills fcl dependencies This fixes the Buffer is not defined and Module n

Dec 8, 2022

A plugin that lets you override the Webpack modules public path in webpage runtime.

dynamic-public-path-plugin A plugin that lets you override the Webpack modules public path in webpage runtime. plugin : webpack-runtime-public-path-pl

Jan 25, 2022

Document Typescript React components with TSDoc and export Storybook-friendly JSON 🤖

Document Typescript React components with TSDoc and export Storybook-friendly JSON 🤖

✨ Document React components with @prop ✨ react-tsdoc 🤖 react-tsdoc is an tool to extract information from React Typescript component files with TSDoc

Oct 15, 2022

Extract the JSON payload from SHC QR codes (i.e Québec Covid Vaccination QR Codes)

Extract the JSON payload from SHC QR codes (i.e Québec Covid Vaccination QR Codes)

shc-extractor Extract the JSON payload from SHC QR Codes (i.e Québec COVID Vaccination QR Codes) Introduction Dans les prochains jours/semaines, les q

Dec 16, 2022

A React application for AddressBook to manage contacts on web. It will use JSON-server to create backend apis.

Available Scripts In the project directory, you can run: npm install To install all related packages npm start Runs the app in the development mode. O

Jan 10, 2022

🌊 A flexible and fun JavaScript file upload library

🌊 A flexible and fun JavaScript file upload library

A JavaScript library that can upload anything you throw at it, optimizes images for faster uploads, and offers a great, accessible, silky smooth user

Dec 31, 2022

This is a starter file with base SvelteKit skeleton configurations with Open Props, Jit Props, and PostCSS configured.

create-svelte Everything you need to build a Svelte project, powered by create-svelte; Creating a project If you're seeing this, you've probably alrea

Jul 22, 2022

Glob - Github action to match glob patterns and retrieve the relative file paths.

Glob - Github action to match glob patterns and retrieve the relative file paths.

Dec 12, 2022
Releases(2.1.21)
Owner
Avansai
Avansai
JSON Hero is an open-source, beautiful JSON explorer for the web that lets you browse, search and navigate your JSON files at speed. 🚀

JSON Hero makes reading and understand JSON files easy by giving you a clean and beautiful UI packed with extra features.

JSON Hero 7.2k Jan 9, 2023
This is a simpler project than the full webpack source code, and you can understand the design ideas in webpack through it

my-webpack 这是一个简化版的webpack,旨在于理解webpack的设计原理以及webpack当中 loader和plugin的区别,运行方式。 运行步骤如下(方案一): 切换到my-webpack目录,运行npm install 切换到test目录,运行npm install 在tes

null 14 Sep 30, 2022
Webpack is an open-source JavaScript module bundler. This includes basic setup files to help me not redo all the setups for webpack when starting a new project.

Webpack Setup Webpack is an open-source JavaScript module bundler. It is made primarily for JavaScript, but it can transform front-end assets such as

Nemwel Boniface 14 Jun 23, 2022
Webpack plugin to tree-shake and minify JSON modules

webpack-json-access-optimizer Optimize JSON modules that are referenced via accessor function. For example, i18n locale JSONs. Features Tree shaking R

hiroki osame 33 Oct 23, 2022
shouganaiyo-loader is a cross-platform Frida-based Node.js command-line tool that forces Java processes to load a Java/JVMTI agent regardless of whether or not the JVM has disabled the agent attach API.

shouganaiyo-loader: Forced Entry for Java Agents shouganaiyo-loader is a cross-platform Frida-based Node.js command-line tool that forces Java process

NCC Group Plc 20 Sep 19, 2022
IPL Loader to load IPL's as soon as Player is in range. This also fixes, IPL's not showing on reconnect in debug mode.

ALT-V IPL-Loader IPL Loader to load IPL’s as soon as Player is in range of the IPL Coordinates. This also fixes, IPL’s not showing on reconnect in deb

null 3 Oct 9, 2022
A complete set up of the React application with Typescript, Webpack 5, Babel v7, SSR, Code Splitting and HMR.

Getting Started with react-final-boilerplate Clone the code npm install You are good to go with React Application. Open http://localhost:3000/ and you

null 24 Dec 22, 2022
Single Page Application with React, React Router, PostCSS, Webpack, Docker and Docker Compose.

spa-store Single Page Application with React, React Router, PostCSS, Webpack, Docker and Docker Compose. Contributing Feedback Roadmap Releases Check

Luis Falcon 2 Jul 4, 2022
This a todo list project that uses webpack. In this project you will find features like adding tasks, deleting tasks, maintaining localstorage, marking tasks completed and clearing all completed tasks.

webpack-Todo list This a todo list project that uses webpack. In this project you will find features like adding tasks, deleting tasks, maintaining lo

Natnael Demelash 2 Jun 15, 2022
React Starter Kit — isomorphic web app boilerplate (Node.js, Express, GraphQL, React.js, Babel, PostCSS, Webpack, Browsersync)

React Starter Kit — "isomorphic" web app boilerplate React Starter Kit is an opinionated boilerplate for web development built on top of Node.js, Expr

Kriasoft 21.7k Dec 30, 2022