How to define the property file in node js? - node.js

I have found an article about properties file reader in node js here:
https://www.npmjs.com/package/properties-reader
There is a module as 'properties-reader'. But, I'm unable to understand how to define the property file. Should it be a json?

It's an ini format, as described here:
# contents of properties file
[main]
some.thing = foo
[blah]
some.thing = bar

Its not a Json format, but in ini format.
Steps to set up properties file and to read it from your node module:
make any properties file such as app.properties inside your project directory. The file may contain data like:
\#comment(ignored)
sever.port=3000
Run the following command to install properties-reader locally:
npm i properties-reader
once done use the properties-reader like this:
const PropertiesReader = require('properties-reader');
const prop = PropertiesReader('path/to/app.properties');
/*gets property from path/to/app.properties
You can also export this function using module.exports*/
getProperty = (pty) => {return prop.get(pty);}
//call the getProperty method
console.log(getProperty('server.port')); //3000
Easy as that!

Related

How to mock only one constant exported from a config file with many constants using Jest

I have a config file with simplified content (it contains several more constants) like this:
export const appTitle = "Drzewo wyboru"
export const warnings ={
missing:" Kryterium"
duplicate: "Duplikacja"
In a test file I have written a mock like this:
jest.mock('../../../src/config',()=>({AppTitle:'abc123test'}));
The problem is that other items in the config file are necessary to correctly render the tested component as well - so this mock breaks a test.
I have read about possible uses of jest.requireActual but it works with objects and in config I have loose items.
How could I mock only this one item, leaving the rest intact without changing the structure of my config file?
You can do partial mocking for your module:
jest.mock('../../../src/config',() => {
const originalModule = jest.requireActual('../../../src/config');
return {
__esModule: true,
...originalModule,
AppTitle: 'abc123test',
};
});
More information can be found in the official doc here.
(Your example states that you want to mock out AppTitle, yet the actual module contains appTitle which is a different property, I am not sure if this was a mistake, but if it was I can update my answer)

How can I read json values from a file?

So basically I have these json values in my config.json file, but how can I read them from a .txt file, for example:
{"prefix": $}
This would set a variable configPrefix to $. Any help?
You can use require() to read and parse your JSON file in one step:
let configPrefix = require("./config.json").prefix;
Or, if you wanted to get multiple values from that config:
const configData = require("./config.json");
let configPrefix = configData.prefix;
If your data is not actually JSON formatted, then you have to read the file yourself with something like fs.readFile() or fs.readFileSync() and then parse it yourself according to whatever formatting rules you have for the file.
If you are going to be reading this file just as the start of the program then go ahead and use require or import if you have babel. just a tip, suround the require with a try catch block to handle possible errors.
let config
try {
config = require('path.to.file.json')
} catch (error) {
// handle error
config = {}
}
If you will be changing this file externally and you feel the need to source it then apart from reading it at the start you will need a function that uses fs.readFile. consider doing it like this and not with readFileAsync unless you need to block the program until you are done reading the config file.
After all of that you can do const configPrefix = config.prefix which will have the value '$'.

How can I access command options in separate files?

I'm using commander to specify some commands and options for my global node module in the index.js file of the project (like shown in the example).
I know that I can easily check if a command was used by using the following code:
if (program.peppers) {
console.log('-peppers was used')
}
But how can I check those properties in other files? I've already tried exporting program and requiring it in those other files, but it doesn't seem to work.
Let's say I want to check if an option was used in a different file than in the one in which I've defined them. How should I do that?
You could pass the parsed program to the files/functions that need the parsed arguments or you can export the parsed arguments program instance
File index.js
var program = require('./program');
if (program.peppers) {
console.log('-peppers was used')
}
File program.js
var program = require('commander');
program
.version('0.0.1')
.option('-p, --peppers', 'Add peppers')
.option('-P, --pineapple', 'Add pineapple')
.option('-b, --bbq-sauce', 'Add bbq sauce')
.option('-c, --cheese [type]', 'Add the specified type of cheese [marble]', 'marble')
.parse(process.argv);
module.exports = program;
Invoking index.js from command line:
> node index.js -p
Yields the output
-peppers was used

Vert.x how to call a file in module

I have a module like this structure:
module_root/
mod.json
filestore/myfile
com/my/www/my.groovy(Compiled to my.class)
I want to call filestore/myfile in my.groovy. I tried many methods to access the file, but I failed.
First, I try to use relative path. Both ../../../filestore/myfile and filestore/myfile failed. No such file or directory.
new FileInputStream('../../../filestore/myfile').withStream {
// ...
}
Then I try to use absolute path, I don't know how to get the module's absolute path. I try to get the my.groovy path use this code:
scriptFile = getClass().protectionDomain.codeSource.location.path
But when I exec vertx runzip mymodule.zip, I get an exception:
java.lang.NullPointerException: Cannot get property 'location' on null object
How to do this?
for me this works..please let me know if works for you:
this is js, I don't know groovy but I suppose than must be similar
var CURRENT-DIRECTORY = new java.io.File("").getAbsolutePath()
then you can use string concatenation
CURRENT-DIRECTORY+"/filestore/myfile/mysuperFile.groovy" <--notice the /
remember than the response is a buffer, maybe you must be convert this to string
return response.toString()
good luck

How does this npm build work?

https://github.com/apigee-127/swagger-converter
I see this code:
var convert = require('swagger-converter');
var fs = require('fs');
var resourceListing = JSON.parse(fs.readFileSync('/path/to/petstore/index.json').toString());
var apiDeclarations = [ JSON.parse(fs.readFileSync('/path/to/petstore/pet.json').toString()),
JSON.parse(fs.readFileSync('/path/to/petstore/user.json').toString()),
JSON.parse(fs.readFileSync('/path/to/petstore/store.json').toString())
];
var swagger2Document = convert(resourceListing, apiDeclarations);
console.log(JSON.stringify(swagger2Document, null, 2));
I'm confsued as to what exactly I'm supposed to do here to run this? Do I start a node http server?
To run the file you pasted, just save the code into a file like script.js. Then from the command line (with node installed) run node script.js. That will run the file. Here's a breakdown of what it's doing:
var convert = require('swagger-converter');
This line gets reference to the swagger-converter module that you linked to. That module is designed to allow you to convert swagger documents into JSON.
var fs = require('fs');
This line gets reference to the node built-in filesystem module (fs for short). It provides an API for interacting with the filesystem on your machine when the script is running.
var resourceListing = JSON.parse(fs.readFileSync('/path/to/petstore/index.json').toString());
This line could be broken down to:
var indexContent = fs.readFileSync('/path/to/petstore/index.json');
JSON.parse(indexContent.toString());
readFileSync returns the contents of the index.json file as a buffer object, which is easily turned into a simple string with the call to .toString(). Then they pass it to JSON.parse which parses the string and turns it into a simple JavaScript object.
Fun Fact: They could have skipped those steps with a simple var resourceListing = require('/path/to/petstore/index.json');. Node knows how to read JSON files and automatically turn them into JavaScript objects. You need only pass the path to require.
var apiDeclarations = [ JSON.parse(fs.readFileSync('/path/to/petstore/pet.json').toString()),
JSON.parse(fs.readFileSync('/path/to/petstore/user.json').toString()),
JSON.parse(fs.readFileSync('/path/to/petstore/store.json').toString())
];
This bit of code does the same thing as the resourceListing except it creates an array of three JavaScript objects based on those JSON files. They also could have used require here to save a bit of work.
Then finally they use the converter to do the conversion and then they log that data to the terminal where your script is running.
var swagger2Document = convert(resourceListing, apiDeclarations);
console.log(JSON.stringify(swagger2Document, null, 2));
JSON.stringify is the opposite of JSON.parse. stringify turns a JavaScript object into a JSON string whereas parse turns a JSON string into a JavaScript object.

Resources