Javascript read property files

Installation

The properties are then accessible either by fully qualified name, or if the property names are in dot-delimited notation, they can be access as an object:

// fully qualified name var property = properties.get('some.property.name'); // by object path var property = properties.path().some.property.name; 

To read more than one file, chain calls to the .append() method:

properties.append('/another.file').append('/yet/another.file'); 

To read properties from a string, use the .read() method:

properties.read('some.property = Value \n another.property = Another Value'); 

To set a single property into the properties object, use .set() :

properties.set('property.name', 'Property Value'); 

When reading a .ini file, sections are created by having a line that contains just a section name in square brackets. The section name is then prefixed to all property names that follow it until another section name is found to replace the current section.

# contents of properties file [main] some.thing = foo [blah] some.thing = bar // reading these back from the properties reader properties.get('main.some.thing') == 'foo'; properties.get('blah.some.thing') == 'bar'; // looping through the properties reader properties.each((key, value) => < // called for each item in the reader, // first with key=main.some.thing, value=foo // next with key=blah.some.thing, value=bar >); // get all properties at once expect(properties.getAllProperties()).toEqual(< 'main.some.thing': 'foo', 'blah.some.thing': 'bar', >) 

Checking for the current number of properties that have been read into the reader:

var propertiesCount = properties.length; 

The length is calculated on request, so if accessing this in a loop an efficiency would be achieved by caching the value.

Читайте также:  Python format padding zero

When duplicate names are found in the properties, the first one read will be replaced with the later one.

To get the complete set of properties, either loop through them with the .each((key, value) => <>) iterator or use the convenience method getAllProperties to return the complete set of flattened properties.

Saving changes

Once a file has been read and changes made, saving those changes to another file is as simple as running:

// async/await ES6 const propertiesReader = require('properties-reader'); const props = propertiesReader(filePath, writer:  saveSections: true >>); await props.save(filePath); // ES5 callback styles props.save(filePath, function then(err, data)  . >); // ES5 promise style props.save(filePath).then(onSaved, onSaveError);

To output the properties without any section headings, set the saveSections option to false

Data Types

Properties will automatically be converted to their regular data types when they represent true/false or numeric values. To get the original value without any parsing / type coercion applied, use properties.getRaw(‘path.to.prop’) .

FAQ / Breaking Changes

Duplicate Section Headings

From version 2.0.0 the default behaviour relating to multiple [section] blocks with the same name has changed so combine the items of each same-named section into the one section. This is only visible when saving the items (via reader.save() ).

To restore the previous behaviour which would allow duplicate [. ] blocks to be created, supply an appender configuration with the property allowDuplicateSections set to true .

const propertiesReader = require('properties-reader'); const props = propertiesReader(filePath, 'utf-8',  allowDuplicateSections: true >);

Contributions

If you find bugs or want to change functionality, feel free to fork and pull request.

Источник

Properties File — Nodejs Read & Write

This tutorial explains step by step to read and write a properties file in Javascript nodejs for example with properties-reader node package You learned to read properties file with key and values and also write key and values to the properties file.

In this tutorial, How to read and write a properties file content in Nodejs Application.

Usually, Properties files are used to store environment information as well as settings related to users or the environment.

  • Create a folder nodejs-reader
  • Inside a folder, Run npm init command to create a nodejs scaffolding application

This will create a basic nodejs folder Next, Install properties-reader npm library

Let’s see an read and write properties file in the nodejs application

Read properties file in Nodejs Application

In this example, you will learn how to Read key and its values from a properties file and display it to console

Let’s declare the properties file

  • Create a new javascript file — propertiesreader.js
  • import properties-reader module into javascript using the required method.
  • Create an object for PropertiesReader by giving properties file location
  • This object has all properties keys and values
  • You can get value using the get method with the given key and print to console.

propertiesreader.js:

It has each method to iterate all objects in a file

  • created a File object with an absolute path
  • Create BufferedReader using FileReader object
  • get the First line of the properties file using readLine of BufferedReader
  • Loop using while loop until the end of the line reached
  • Print each line
 >); properties.set("key1", "value1") properties.set("database", "postgres") properties.save(propertiesPah, function then(err, data) < if (err) < console.log("error in write a properties file") >console.log("saved data to properties file") >); 

How to write a key and values to a properties file in java

In this example, You can read and write a property using

  • Import PropertiesReader into javascript
  • Create a writer object using PropertiesReader with path and writer object
    • You can add new properties or update existing properties if the properties file exists

    Here is a complete example read and write a properties file

     >); console.log(writer.get("database")); console.log(writer.get("hostname")); console.log(writer.get("username")); console.log(writer.get("password")); writer.each((key, value) => < console.log(key + ":" + value); >); writer.set("key1", "value1") writer.set("database", "value1") writer.save(propertiesPath, function then(err, data) < if (err) < console.log("error in write a properties file") >console.log("saved data to properties file") >); 
    You learned to read a properties file with keys and values as well and also write keys and values to a properties file in NodeJS javascript application

    Источник

    How to access a property file using «javascript»

    How do I access a property file using javascript. Normally property file is a xml based file. I java we access a property file like this:

    Properties prop = new Properties(); fis = getClass().getResourceAsStream("props.xml"); if (fis != null) < prop.loadFromXML(fis); >String dbUrl = prop.getProperty("dburl"); 

    @ Joey if you don’t know the answer you’re the joke here,so please get lost. @ nickf I put quotes because to highlight it.

    4 Answers 4

    JavaScript can’t load files, as part of its security model. It can retrieve XML from the server using AJAX, but it can’t read files from the client computer.

    You can’t load any files from the users computer with javascript in the browser.

    If the file is from your own server you can load it, like any other ajax, with XMLHttpRequest.

    Javascript doesn’t use property files, as, either it has all the information it needs in the javascript files or in the html, or it will make an XMLHTTPRequest call to get the information from the server.

    The server can look at the property file, and may use information passed in from the request, such as the header information, to know more about the client, to determine what information to pass back.

    So, if you want to pass back some localized information, the server would have to get that from the browser request and then it could send back just what is needed for that transaction.

    Javascript is different from java, so one limit is that javascript cannot read from the hard drive of the user, and since it is a webpage, the user wouldn’t have the property file installed, it would still be on the server.

    Javascript can only make requests to the address that that script came from, so there is a second sandbox rule that has to be met.

    You may want to better understand javascript, then try to rephrase your question.

    Источник

    How to read a properties file in javascript from project directory?

    Here I want main.js to load config.properties file in the beginning and get key-value pairs.

    Have anyone done something like this?

    6 Answers 6

    There is a super simple way to do this, along the lines of sowbug’s answer, but which doesn’t need any XHR or file reading.

    Step 1. Create resource/config.js like so:

    Step 2. Include this file in your index.html:

    Step 3. Access your options directly from your main.js (or anywhere):

    The answer does not resolve the problem. I also have a properties file used in 3rd party code. I cannot rewrite it to json as you suggested.

    You can use messageResource.js, a simple javascript library created by me for loading properties file.

    1) Include messageResource.js in your index.html.

    2) You can get key-value pairs of config.properties from main.js using the following code.

    // initialize messageResource.js messageResource.init(< // path to directory containing config.properties filePath : 'resource' >); // load config.properties file messageResource.load('config', function()< // load file callback // get value corresponding to a key from config.properties var value = messageResource.get('key', 'config'); >); 

    @Khan I’ve tried the exact process you mentioned in your answer but I’m having the same problem as sarwar026.

    First make sure config.properties is accessible via a url. Before calling messageResource.get function you should load the properties file using the below code. messageResource.load(‘config’, function()< // load file callback >);

    I know this was accepted as answered a long time ago but there never was a true «as is» .properties answer. There was only don’t use that and instead convert it to .js. Obviously that would be preferable but not always possible. If it’s not possible, say in a Java application that also has JavaScript somewhere and the .properties file is very much used by Java and shared by the JavaScript to avoid duplication, then an actual .properties answer would be best.

    If you are using ES6, React, Vue, Angular, etc. then you can import it. Let’s say it’s a list of URLs in a URL.properties file. There is no need to specify the path even in JavaScript but a unique name is required.

    The syntax can be tricky for keys with dots in them, such as widgetAPI.dev. You can’t simply invoke it as URL.widgetAPI.dev. Since the properties file (content) is an object once it gets to JavaScript so you can reference it like any Object key, such as:

    console.log(URL['widgetAPI.dev']) 

    If you are not in ES6, jQuery has libraries and there is always the ubiquitous messageResource already mentioned.

    Источник

Оцените статью