Giter VIP home page Giter VIP logo

conf's Introduction

conf

Simple config handling for your app or module

All you have to care about is what to persist. This module will handle all the dull details like where and how.

It does not support multiple processes writing to the same store.
I initially made this tool to let command-line tools persist some data.

If you need this for Electron, check out electron-store instead.

Install

npm install conf

Usage

import Conf from 'conf';

const config = new Conf({projectName: 'foo'});

config.set('unicorn', 'πŸ¦„');
console.log(config.get('unicorn'));
//=> 'πŸ¦„'

// Use dot-notation to access nested properties
config.set('foo.bar', true);
console.log(config.get('foo'));
//=> {bar: true}

config.delete('unicorn');
console.log(config.get('unicorn'));
//=> undefined

Or create a subclass.

API

Changes are written to disk atomically, so if the process crashes during a write, it will not corrupt the existing config.

Conf(options?)

Returns a new instance.

options

Type: object

defaults

Type: object

Default values for the config items.

Note: The values in defaults will overwrite the default key in the schema option.

schema

Type: object

JSON Schema to validate your config data.

Under the hood, the JSON Schema validator ajv is used to validate your config. We use JSON Schema draft-07 and support all validation keywords and formats.

You should define your schema as an object where each key is the name of your data's property and each value is a JSON schema used to validate that property. See more here.

Example:

import Conf from 'conf';

const schema = {
	foo: {
		type: 'number',
		maximum: 100,
		minimum: 1,
		default: 50
	},
	bar: {
		type: 'string',
		format: 'url'
	}
};

const config = new Conf({
	projectName: 'foo',
	schema
});

console.log(config.get('foo'));
//=> 50

config.set('foo', '1');
// [Error: Config schema violation: `foo` should be number]

Note: The default value will be overwritten by the defaults option if set.

migrations

Type: object

Important: I cannot provide support for this feature. It has some known bugs. I have no plans to work on it, but pull requests are welcome.

You can use migrations to perform operations to the store whenever a project version is upgraded.

The migrations object should consist of a key-value pair of 'version': handler. The version can also be a semver range.

Example:

import Conf from 'conf';

const store = new Conf({
	projectName: 'foo',
	projectVersion: …,
	migrations: {
		'0.0.1': store => {
			store.set('debugPhase', true);
		},
		'1.0.0': store => {
			store.delete('debugPhase');
			store.set('phase', '1.0.0');
		},
		'1.0.2': store => {
			store.set('phase', '1.0.2');
		},
		'>=2.0.0': store => {
			store.set('phase', '>=2.0.0');
		}
	}
});

Note: The version the migrations use refers to the project version by default. If you want to change this behavior, specify the projectVersion option.

beforeEachMigration

Type: Function
Default: undefined

The given callback function will be called before each migration step.

The function receives the store as the first argument and a context object as the second argument with the following properties:

  • fromVersion - The version the migration step is being migrated from.
  • toVersion - The version the migration step is being migrated to.
  • finalVersion - The final version after all the migrations are applied.
  • versions - All the versions with a migration step.

This can be useful for logging purposes, preparing migration data, etc.

Example:

import Conf from 'conf';

console.log = someLogger.log;

const mainConfig = new Conf({
	projectName: 'foo1',
	beforeEachMigration: (store, context) => {
		console.log(`[main-config] migrate from ${context.fromVersion} β†’ ${context.toVersion}`);
	},
	migrations: {
		'0.4.0': store => {
			store.set('debugPhase', true);
		},
	}
});

const secondConfig = new Conf({
	projectName: 'foo2',
	beforeEachMigration: (store, context) => {
		console.log(`[second-config] migrate from ${context.fromVersion} β†’ ${context.toVersion}`);
	},
	migrations: {
		'1.0.1': store => {
			store.set('debugPhase', true);
		},
	}
});

configName

Type: string
Default: 'config'

Name of the config file (without extension).

Useful if you need multiple config files for your app or module. For example, different config files between two major versions.

projectName

Type: string

Required unless you specify the cwd option.

You can fetch the name field from package.json.

projectVersion

Type: string\

Required if you specify the migration option.

You can fetch the version field from package.json.

cwd

Type: string
Default: System default user config directory

You most likely don't need this. Please don't use it unless you really have to. By default, it will pick the optimal location by adhering to system conventions. You are very likely to get this wrong and annoy users.

Overrides projectName.

The only use-case I can think of is having the config located in the app directory or on some external storage.

encryptionKey

Type: string | Uint8Array | TypedArray | DataView
Default: undefined

Note that this is not intended for security purposes, since the encryption key would be easily found inside a plain-text Node.js app.

Its main use is for obscurity. If a user looks through the config directory and finds the config file, since it's just a JSON file, they may be tempted to modify it. By providing an encryption key, the file will be obfuscated, which should hopefully deter any users from doing so.

When specified, the store will be encrypted using the aes-256-cbc encryption algorithm.

fileExtension

Type: string
Default: 'json'

Extension of the config file.

You would usually not need this, but could be useful if you want to interact with a file with a custom file extension that can be associated with your app. These might be simple save/export/preference files that are intended to be shareable or saved outside of the app.

clearInvalidConfig

Type: boolean
Default: false

The config is cleared if reading the config file causes a SyntaxError. This is a good behavior for unimportant data, as the config file is not intended to be hand-edited, so it usually means the config is corrupt and there's nothing the user can do about it anyway. However, if you let the user edit the config file directly, mistakes might happen and it could be more useful to throw an error when the config is invalid instead of clearing.

serialize

Type: Function
Default: value => JSON.stringify(value, null, '\t')

Function to serialize the config object to a UTF-8 string when writing the config file.

You would usually not need this, but it could be useful if you want to use a format other than JSON.

deserialize

Type: Function
Default: JSON.parse

Function to deserialize the config object from a UTF-8 string when reading the config file.

You would usually not need this, but it could be useful if you want to use a format other than JSON.

projectSuffix

Type: string
Default: 'nodejs'

You most likely don't need this. Please don't use it unless you really have to.

Suffix appended to projectName during config file creation to avoid name conflicts with native apps.

You can pass an empty string to remove the suffix.

For example, on macOS, the config file will be stored in the ~/Library/Preferences/foo-nodejs directory, where foo is the projectName.

accessPropertiesByDotNotation

Type: boolean
Default: true

Accessing nested properties by dot notation. For example:

import Conf from 'conf';

const config = new Conf({projectName: 'foo'});

config.set({
	foo: {
		bar: {
			foobar: 'πŸ¦„'
		}
	}
});

console.log(config.get('foo.bar.foobar'));
//=> 'πŸ¦„'

Alternatively, you can set this option to false so the whole string would be treated as one key.

import Conf from 'conf';

const config = new Conf({
	projectName: 'foo',
	accessPropertiesByDotNotation: false
});

config.set({
	`foo.bar.foobar`: 'πŸ¦„'
});

console.log(config.get('foo.bar.foobar'));
//=> 'πŸ¦„'

watch

type: boolean
Default: false

Watch for any changes in the config file and call the callback for onDidChange or onDidAnyChange if set. This is useful if there are multiple processes changing the same config file.

configFileMode

Type: number
Default: 0o666

The mode that will be used for the config file.

You would usually not need this, but it could be useful if you want to restrict the permissions of the config file. Setting a permission such as 0o600 would result in a config file that can only be accessed by the user running the program.

Note that setting restrictive permissions can cause problems if different users need to read the file. A common problem is a user running your tool with and without sudo and then not being able to access the config the second time.

Instance

You can use dot-notation in a key to access nested properties.

The instance is iterable so you can use it directly in a for…of loop.

.set(key, value)

Set an item.

The value must be JSON serializable. Trying to set the type undefined, function, or symbol will result in a TypeError.

.set(object)

Set multiple items at once.

.get(key, defaultValue?)

Get an item or defaultValue if the item does not exist.

.reset(...keys)

Reset items to their default values, as defined by the defaults or schema option.

Use .clear() to reset all items.

.has(key)

Check if an item exists.

.delete(key)

Delete an item.

.clear()

Delete all items.

This resets known items to their default values, if defined by the defaults or schema option.

.onDidChange(key, callback)

callback: (newValue, oldValue) => {}

Watches the given key, calling callback on any changes.

When a key is first set oldValue will be undefined, and when a key is deleted newValue will be undefined.

Returns a function which you can use to unsubscribe:

const unsubscribe = conf.onDidChange(key, callback);

unsubscribe();

.onDidAnyChange(callback)

callback: (newValue, oldValue) => {}

Watches the whole config object, calling callback on any changes.

oldValue and newValue will be the config object before and after the change, respectively. You must compare oldValue to newValue to find out what changed.

Returns a function which you can use to unsubscribe:

const unsubscribe = conf.onDidAnyChange(callback);

unsubscribe();

.size

Get the item count.

.store

Get all the config as an object or replace the current config with an object:

conf.store = {
	hello: 'world'
};

.path

Get the path to the config file.

FAQ

How is this different from configstore?

I'm also the author of configstore. While it's pretty good, I did make some mistakes early on that are hard to change at this point. This module is the result of everything I learned from making configstore. Mainly where the config is stored. In configstore, the config is stored in ~/.config (which is mainly a Linux convention) on all systems, while conf stores config in the system default user config directory. The ~/.config directory, it turns out, often have an incorrect permission on macOS and Windows, which has caused a lot of grief for users.

Can I use YAML or another serialization format?

The serialize and deserialize options can be used to customize the format of the config file, as long as the representation is compatible with utf8 encoding.

Example using YAML:

import Conf from 'conf';
import yaml from 'js-yaml';

const config = new Conf({
	projectName: 'foo',
	fileExtension: 'yaml',
	serialize: yaml.safeDump,
	deserialize: yaml.safeLoad
});

Related

  • electron-store - Simple data persistence for your Electron app or module
  • cache-conf - Simple cache config handling for your app or module

conf's People

Contributors

bendingbender avatar brandon93s avatar buddydvd avatar ciberusps avatar deniscarriere avatar diyews avatar dreamorosi avatar edenhermelin avatar fregante avatar ignigena avatar mifi avatar ncallaway avatar nhevia avatar niktekusho avatar pepicrft avatar peterdanis avatar popod avatar rafaelramalho19 avatar richienb avatar rpadaki avatar samverschueren avatar scottbot95 avatar sindresorhus avatar snosme avatar theaifam5 avatar therealsyler avatar trodi avatar vaaski avatar weswigham avatar yaodingyd avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

conf's Issues

Trigger `onDidChange` when the file is altered

Issuehunt badges

See #47 for an initial attempt that went stale. Please take into account all the feedback given there if you intend to take on the issue.

Part of this task is also to bring the docs over to electron-store to resovle sindresorhus/electron-store#39.


Note: This is not an easy issue. It requires you to have good JavaScript and Node.js experience. I expect you to do a good job. Instead of asking to many questions, present solutions. The point of a issue bounty is to give me less work, not more. πŸ™Œ


IssueHunt Summary

yaodingyd yaodingyd has been rewarded.

Backers (Total: $80.00)

Submitted pull Requests


Tips


IssueHunt has been backed by the following sponsors. Become a sponsor

Uncaught TypeError: Cannot read property 'filename' of undefined

This just took forever to track down. Been trying to get some Karma tests working in an Electron project and have been getting these errors.

# The initial error

WARNING in ./~/any-promise/register.js
24:14-37 Critical dependency: the request of a dependency is an expression

WARNING in ./~/conf/index.js
21:27-43 Critical dependency: the request of a dependency is an expression
Child html-webpack-plugin for "index.html":
         Asset    Size  Chunks  Chunk Names
    index.html  567 kB       0
    chunk    {0} index.html 541 kB [entry]
        [0] ./~/lodash/lodash.js 540 kB {0}
        [1] ./~/html-webpack-plugin/lib/loader.js!./src/index.ejs 1.11 kB {0}
        [2] (webpack)/buildin/module.js 517 bytes {0}
Electron 1.7.4 (Node 7.9.0) ERROR
# Initial Error
  Uncaught TypeError: Cannot read property 'filename' of undefined
  at webpack:///~/conf/index.js:13:0 <- index.js:27358
# ran `npm i -S conf` and it switched to this

WARNING in ./~/any-promise/register.js
24:14-37 Critical dependency: the request of a dependency is an expression

WARNING in ./~/conf/index.js
21:27-43 Critical dependency: the request of a dependency is an expression
Child html-webpack-plugin for "index.html":
         Asset    Size  Chunks  Chunk Names
    index.html  567 kB       0
    chunk    {0} index.html 541 kB [entry]
        [0] ./~/lodash/lodash.js 540 kB {0}
        [1] ./~/html-webpack-plugin/lib/loader.js!./src/index.ejs 1.11 kB {0}
        [2] (webpack)/buildin/module.js 517 bytes {0}
Electron 1.7.4 (Node 7.9.0) ERROR
# this is what changed 
  Uncaught Error: Cannot find module "."
  at webpack:///~/conf/index.js:21:0 <- index.js:27366

It is related to import Store from 'electron-store';

After commenting out that import and replacing it with the below code, the Karma spec functions as expected:

class Store {
  constructor (options = {}) {
    const opt = {
    };

    this.options = Object.assign({}, opt, options);
    this.data = {};
  }

  set (key, value) {
    this.data[key] = value;
  }

  has (key) {
    return !!this.data[key];
  }
}

Any help resolving this would be much appreciated.

Thanks!

Feature Request: Allow schema to be free-form

Currently the implementation expects that the schema provided is the properties of an object type. For most cases, this is probably fine, but I am finding it a little limiting because I am unable to define top-level properties, such as required, propertyNames, additionalProperties, et al.

As such, I feel like projects could benefit from being able to define their own schema at any level, or default to the preexisting behavior: if the top level of the given schema doesn't define either definitions or type, then assume it's the original schema style and wrap it in its own properties key. Otherwise, allow the schema writer to define any level of the JSON schema.

I'd be willing to work on this, but only if there is buy in.

Add the ability to unsubscribe from `onDidChange`

im using the electron-store package for a electron/react app and on componentDidMount im calling the onDidChange method of the store the problem is im getting an error when the component is unmounted because the callback references the component, so a unsubscribe thing would be good to prevent this kind of issue.

i can help adding it, i already have some vague ideas on how this could be implemented, just want to be sure that something like this would be merged so that i don't waste my time.

Migration creates wrong internal version number

The following code should create an config.json file with the config version number "0.0.1", instead it stores an internal version of "1.0.0":

const Conf = require('conf')

new Conf({
  migrations: {
    "0.0.1": store => {
      store.set('a', 'foo');
    }
  }
});

config.json:

{
	"a": "foo",
	"__internal__": {
		"migrations": {
			"version": "1.0.0"
		}
	}
}

Uncaught Error: Cannot find module "."

I am using this via electron-store and getting this error:

screen shot 2017-06-26 at 2 23 06 pm

Stacktrace:

Uncaught Error: Cannot find module "."
    at webpackMissingModule (index.js:21)
    at ElectronStore.Conf (index.js:21)
    at ElectronStore (index.js:20)
    at new CustomComponent (App.js:36)
    at ReactCompositeComponent.js:294
    at measureLifeCyclePerf (ReactCompositeComponent.js:75)
    at ReactCompositeComponentWrapper._constructComponentWithoutOwner (ReactCompositeComponent.js:293)
    at ReactCompositeComponentWrapper._constructComponent (ReactCompositeComponent.js:279)
    at ReactCompositeComponentWrapper.mountComponent (ReactCompositeComponent.js:187)
    at Object.mountComponent (ReactReconciler.js:45)

The library seems to not be multithread safe

I'm using conf inside in an electron application inside some webworkers.

The reason why i'm not using electron-store is that it does not work in webworkers.

conf seems to have problem in initialising the config file from different webworkers. The underlying problem seems to be related with the write-file-atomic package, function writeFileSync

What is it doing: (i assume for avoiding having corrupted files)

  • creating a tmp config file
  • writing in the file
  • renaming it

What can happen in a multithread environment:

  • Webworker 1 -> create tmp file
  • Webworker 2 -> create same tmp file (apparently the file name depends on the pid, which is the same from all the webworkers)
  • Webworker 1 -> set file permission, write the file and delete it
  • Webworker 2 -> set file permission, but cannot since the file does not exists anymore. And throw and exception.

The exception i'm getting is:

ENOENT: no such file or directory, chown '/Users/oltreseba/Library/Preferences/project-nodejs/config.json.1638900804'

Can't store Node.js Timeout object

An attempt to store Timeout (a return value from setInterval and setTimeout functions in Node) inside conf results in

TypeError: Converting circular structure to JSON

Example code:

const getTimerObject = () => {
	return config.get("timerObject") || null;
};

const setTimerObject = newTimerObject => {
	config.store = newTimerObject;
	return getTimerObject();
};

const currentInterval = setTimeout(() => console.log("tick"), 3000);

const savedCurrentInterval = setTimerObject(currentInterval); // fails here

Any way I can work around this? I need to store it to be able to cancel it on demand, based on user input. (Purpose: Alfy based Alfred Workflow)

Get all configs

I need get all method for see what includes my config. I have solution maybe it's help.

Pr: #4

Problematic file write upon instantiation

I have a bitbar plugin that gets refreshed every second, 99% of the times it just reads data from the configuration without mutating it in any way.

In conf's constructor there's this line:

this.store = Object.assign(obj(), opts.defaults, this.store);

Which calls store's setter method, which writes back to disk the value of the store we just read. Basically every instantiation causes a write, this may be problematic in some use cases.

This is a problem for me because I have the actual json file stored in the dropbox folder, and being it constantly re-written every second it causes Dropbox to consume 20% of my CPU just for syncing this one file that actually almost never changes.

Is this behavior intentional? If so, would you consider a PR adding an option for disabling it?

New Feature - Read data from the RAM (don't always read the file content)

I dug up a little inside the conf module code and appears to me that each get/read function call uses the fs readFileSync to get the data from the config file.
If I need to constantly check for a value from the app settings it can lead to performance issues. So my approach is to copy the settings to a global variable πŸ‘Ž and only use this module to write the config file when some changes occur.

Are any alternative approach to this problem or do you plan to add a feature to kinda "cache the values" and only reads the file when there are some changes?

Thank you

Consider adding a factory method

I know it's "idiomatic", but I've never been a fan of this style for requiring a class that will only be instantiated once:

const Conf = require('conf');
const config = new Conf();

What about adding a factory method like this:

const conf = require('conf').new();

or even:

const conf = require('conf')();

This could be supplemental to the existing instantiation behavior.

`.set(object)` detection might be wrong

Currently, this is the implementation of .set(key, val) which supports .set(object) as well.

set(key, val) {
    const store = this.store;

    if (val === undefined) {
        Object.keys(key).forEach(k => {
            dotProp.set(store, k, key[k]);
        });
    } else {
        dotProp.set(store, key, val);
    }

    this.store = store;
}

If someone calls set('foo') or set('foo', undefined), Object.keys('foo') returns [0, 1, 2] and the store will look like this

{
    '0': 'f', 
    '1': 'o', 
    '2': 'o'
}

I believe we should add extra checks to the set method. But the first question to answer is, is string the only valid input type for key?

  1. Test that key is of type string or object.
  2. Test if key is of type object AND value is undefined.
    • We could ignore value in this case
    • We could throw an error indicating that it's not possible to provide a value if key is of type object

YAML support

This is a feature request, wondering if we could have YAML support.
Will try an open a PR to add this feature, expect it won't be too much code.

typescript import not work

Hi,
I installed @types/conf and try to use import like this:

import Conf from 'conf'

When I inspect the Conf, it is undefined, if I switch to:

import * as Conf from 'conf'

It works but the tsc complain, @types/conf seem not correctly write for this structure, typescript throw me an error:

[ts] Module '"/Users/x/node_modules/@types/conf/index"' resolves to a non-module entity and cannot be imported using this construct.

Add feature to disable dot-notation

Issuehunt badges

Hi! I'm working on a project that uses reverse-domain naming for namespaces, and we need to store some data with the namespace as the key. Where we'd expect

{
    "cc.xylobol.test": {
        "foo": "bar"
    }
}

we end up with

{
    "cc": {
        "xylobol": {
            "test": {
                "foo": "bar"
            }
        }
    }
}

instead due to the dot-notation. Is there a pre-existing way to disable this? If not, could it be added as a feature?

Thank you in advanced.
Xylobol

IssueHunt Summary

yaodingyd yaodingyd has been rewarded.

Sponsors (Total: $40.00)

Tips

Constructor fails when `/tmp` directory is not writable

{ Error: EACCES: permission denied, open '/tmp/.config/nextjs-nodejs/config.json'
    at Object.openSync (fs.js:443:3)
    at Object.readFileSync (fs.js:343:35)
    at Conf.get store [as store] (/var/app/current/node_modules/conf/index.js:228:18)
    at new Conf (/var/app/current/node_modules/conf/index.js:92:26)
  errno: -13,
  syscall: 'open',
  code: 'EACCES',
  path: '/tmp/.config/nextjs-nodejs/config.json' }

I'm not sure if this would be better raised in env-paths for giving an unwritable path.

However, I think this error would be better deferred until trying to use the Conf instance (e.g. get/set).

x-ref: vercel/next.js#9294

package.json autodetection fails if not used as a direct dependency

As noted in: sindresorhus/electron-store#1 (comment)

Perhaps this can just be mentioned in the README as a caveat, but if no projectName or cwd is provided, conf tries to detect the package.json of the parent package.

However, this uses the module.parent mechanism, which returns the nearest direct dependent, rather than the top level package.

conf/index.js

Line 13 in c5a736b

const parentDir = path.dirname(module.parent.filename);

This can cause issues if a module is using conf via an intermediary.

Jest, console.warn require.cache modification is not permitted

Due to this:
https://github.com/facebook/jest/pull/9841/files
and this:

conf/index.js

Lines 21 to 23 in 410cc14

// Prevent caching of this module so module.parent is always accurate
delete require.cache[__filename];
const parentDir = path.dirname((module.parent && module.parent.filename) || '.');

=>

console.warn
    `require.cache` modification is not permitted

(output'ed many times in the console when unit-testing, with full stacktrace, so quite disruptive, albeit non-fatal unless unit-tests check for CLI output)

Allow config file without extension

I would like to migrate from electron-settings to electron-store. However the default setting file of the former is simply "Settings" (no extension) therefore I would like to be able to instantiate the new store on the same file. I believe they should be compatible.
However, I could not find a way to set a null extension of electron-store as it always append a ..

Improve the TypeScript types

Issuehunt badges

I think the types could still be improved.

  • Would be good to use unknown instead of any here:

    conf/index.d.ts

    Line 210 in bb24cfe

    declare class Conf<T = any> implements Iterable<[keyof T, T[keyof T]]> {
    But it causes error on a valid usage:
     index.test-d.ts:123:13
       βœ–  123:13  Argument of type "debug phase" is not assignable to parameter of type never.
    
  • You cannot use dot-paths with a typed store: config.set('foo.bar', true);. We need to find a way to support that. Could possibly add support for config.set(['foo', 'bar'], true).
  • Reduce duplication if you use both a typed store and the defaults option. Maybe using the const keyword.
  • Could we make the types even stricter?
  • Expose the type of the schema option, so it's easier to define it as a variable before passing it. Currently, you would have to do const schema = {[Key in keyof TypedStore]: Conf.Schema} = {…};.
    readonly schema?: {[P in keyof T]: Schema};
  • Maybe rename the current Schema type to something clearer like SchemaValue, SchemaOptionValue? Need some naming suggestions.

I'm open to other ideas on how to improve the types.


IssueHunt Summary

superjo149 superjo149 has been rewarded.

Backers (Total: $80.00)

Submitted pull Requests


Tips

Namespace 'NodeJS' has no exported member 'TypedArray'.

Hello I am trying to use conf within an electron project using typescript and angular. I am getting the following error when trying to run my app

ERROR in node_modules/conf/index.d.ts(80,53): error TS2694: Namespace 'NodeJS' has no exported member 'TypedArray'.

here is my package.json with the dependencies i have declared:

"devDependencies": {
    "@angular-devkit/build-angular": "0.12.1",
    "@angular/cli": "7.3.3",
    "@angular/common": "7.2.7",
    "@angular/compiler": "7.2.7",
    "@angular/compiler-cli": "7.2.7",
    "@angular/core": "7.2.7",
    "@angular/forms": "7.2.7",
    "@angular/http": "7.2.7",
    "@angular/language-service": "7.2.7",
    "@angular/platform-browser": "7.2.7",
    "@angular/platform-browser-dynamic": "7.2.7",
    "@angular/router": "7.2.7",
    "@ngrx/effects": "^7.4.0",
    "@ngrx/entity": "^7.4.0",
    "@ngrx/router-store": "^7.4.0",
    "@ngrx/store": "^7.4.0",
    "@ngrx/store-devtools": "^7.4.0",
    "@ngx-translate/core": "11.0.1",
    "@ngx-translate/http-loader": "4.0.0",
    "@types/jasmine": "2.8.7",
    "@types/jasminewd2": "2.0.3",
    "@types/mocha": "^5.2.6",
    "@types/node": "^8.9.4",
    "bootstrap": "^4.3.1",
    "chai": "^4.2.0",
    "codelyzer": "4.5.0",
    "conventional-changelog-cli": "2.0.11",
    "core-js": "2.6.1",
    "electron": "4.0.0",
    "electron-builder": "20.36.2",
    "electron-reload": "1.3.0",
    "electron-store": "^3.2.0",
    "jasmine-core": "3.3.0",
    "jasmine-spec-reporter": "4.2.1",
    "karma": "3.1.1",
    "karma-chrome-launcher": "2.2.0",
    "karma-coverage-istanbul-reporter": "2.0.4",
    "karma-jasmine": "2.0.1",
    "karma-jasmine-html-reporter": "1.4.0",
    "mocha": "6.0.2",
    "npm-run-all": "4.1.5",
    "rxjs": "6.4.0",
    "spectron": "5.0.0",
    "ts-node": "7.0.1",
    "tslint": "5.11.0",
    "typescript": "3.2.4",
    "wait-on": "3.2.0",
    "webdriver-manager": "12.1.0",
    "zone.js": "0.8.29",
    "node-sass": "^4.12.0"
  },

I am also running node 12.2.0

How to handle arrays?

Let's say I have a config

{
   "items":[ {"name":"abc"},{"name":"dadd"}]
}

How can I add an item to items array?

Thanks

Add a way to change default config path

I like to keep the config of some tools that use conf under git, and be able to easily use the backed-up configs in unix systems. The current default config path keeps changing, which doesn't lend itself to this. Ideally, I want everything stored under ~/.sindconf/.

Build not passing - silent fail?

I hate to be this guy (chill, it's 0.10.0...) but, you've got an .only that's reporting a non-passing build as passing on [email protected] & [email protected] with a clean npm i.

failing

Builds on


I'd submit a PR, but my head is not where it's supposed to be right now and duty calls (laundry...). Just though I'd let you know. Cheers! πŸ”¨

Add store migrations

Issuehunt badges

See #49 for an initial attempt that went stale. Please take into account all the feedback given there if you intend to take on the issue.

Part of this task is also to bring the docs over to electron-store to resolve sindresorhus/electron-store#19.


Note: This is not an easy issue. It requires you to have good JavaScript and Node.js experience. I expect you to do a good job. Instead of asking to many questions, present solutions. The point of a issue bounty is to give me less work, not more. πŸ™Œ


IssueHunt Summary

rafaelramalho19 rafaelramalho19 has been rewarded.

Backers (Total: $80.00)

Submitted pull Requests


Tips


IssueHunt has been backed by the following sponsors. Become a sponsor

Defaults not applied from schema

Issuehunt badges

I'm using a schema to create my settings, and I've been unable to have conf or electron-config use the defaults provided in the schema.

I've included a reduced test case here:

const Conf = require('conf');

const schema = {
  fizz: {
    type: 'string',
    default: 'buzz',
  },
  foo: {
    type: 'object',
    properties: {
      bar: {
        type: 'string',
        default: 'baz',
      },
    },
  },
};

const config = new Conf({schema});

console.log(config.get('fizz'));    // undefined - should be 'buzz'
console.log(config.get('foo'));     // undefined - should be { bar: 'baz' }
console.log(config.get('foo.bar')); // undefined - should be 'baz'

console.assert(config.get('fizz') === 'buzz');   // Assertion failed
console.assert(config.get('foo.bar') === 'baz'); // Assertion failed

An rough solution to populate defaults from schema is below, but I wouldn't expect to have to do this when using a schema that includes defaults.

function setDefaults(schema, config, key_chain) {
  for (let [key, val] of Object.entries(schema)) {
    let this_key = (key_chain ? key_chain + '.' : '') + key;
    if (val.type === 'object') {
      return setDefaults(val.properties, config, this_key);
    }
    if (!config.has(key) && Object.hasOwnProperty.call(val, 'default')) {
      config.set(this_key, val.default);
    }
  }
}

IssueHunt Summary

Backers (Total: $40.00)

Become a backer now!

Or submit a pull request to get the deposits!

Tips


IssueHunt has been backed by the following sponsors. Become a sponsor

if opts.projectName is defined, prevent to read the pkgPath file

Hi, I would like to suggest whether conf can prevent read the pkgPath file if the opts.projectName is defined.

Now the lib uses this way to set the pkgPath link

options = Object.assign({
  // Can't use `require` because of Webpack being annoying:
  // https://github.com/webpack/webpack/issues/196
  projectName: pkgPath && JSON.parse(fs.readFileSync(pkgPath, 'utf8')).name
}, options);

if (!options.projectName && !options.cwd) {
  throw new Error('Project name could not be inferred. Please specify the `projectName` option.');
}

I think whether it can exam the option first?
The reason is I use the electron-store, and in some cases, I don't know why it loads the pkgPath as root system path (e.g.: /Users/<UserName>/pacakge.json). This will cause the permission issues.
If we can exam the projectName first, we can prevent the conf to automatically load the pkgPath.

So the change would be:

options = Object.assign({
  // Can't use `require` because of Webpack being annoying:
  // https://github.com/webpack/webpack/issues/196
  projectName: options.projectName ? options.projectName : pkgPath && JSON.parse(fs.readFileSync(pkgPath, 'utf8')).name
}, options);

if (!options.projectName && !options.cwd) {
  throw new Error('Project name could not be inferred. Please specify the `projectName` option.');
}

concurrency in ava

Do you recommend using .serial for tests using this module? Any suggestion for a library that uses conf module? It fails since they use the same storage (this module), so I needed to add .serial to those tests.

Missing module.parent in Docker container

The strangest thing happened, everything works in Node 6 & 7, however whenever I bring conf into any of the latest Docker container (ex: node:6) it crashes.

https://github.com/sindresorhus/conf/blob/master/index.js#L13

Error on require

# node
> const Conf = require('conf')
TypeError: Path must be a string. Received null
    at assertPath (path.js:7:11)
    at Object.dirname (path.js:1324:5)
    at Object.<anonymous> (/usr/src/app/node_modules/conf/index.js:13:24)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)

Module parent does not exist

> module.parent
undefined
> module
Module {
  id: '<repl>',
  exports: {},
  parent: undefined,
  filename: null,
  loaded: false,
  children: [],
  paths:
   [ '/usr/src/app/repl/node_modules',
     '/usr/src/app/node_modules',
     '/usr/src/node_modules',
     '/usr/node_modules',
     '/node_modules',
     '/root/.node_modules',
     '/root/.node_libraries',
     '/usr/local/lib/node' ] }

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.