Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to persist user preferences with npm/nodejs command line utility

I'm writing a nodejs cli utility (NPM module intended to be installed globally) that will need to store some user-supplied values. What is the best way to store these values on a system?

For example, should I create my own config file under say: /etc/{my-utility-name}/conf.json and have this directory+file initialized in my install script

(https://npmjs.org/doc/misc/npm-scripts.html)

like image 501
Casey Flynn Avatar asked Oct 18 '13 05:10

Casey Flynn


2 Answers

Looking at the questions and comments i think there are two problems to solve:

  1. Where to save it: If there are user specific settings, then by common pattern in Linux its best saved in the hidden directory in user's home directory. Hence you can best keep it in directory $HOME/.{yourAppName}/someFile

    E.x: Pidgin saves it in: /home/kushal/.purple/...
    ("." prefix to folder name makes it hidden)
       
    You can save it in: /home/$HOME/.myawesomeNPMModule/...

    NOTE: If you are also targeting the windows platform, then you need a platform check and decide which path to use.

    In windows Vista and above it goes in
    $WIN_INSTALLATION_DRIVE\Users\$USER_NAME\AppData\Local\YourAppName...
    In windows XP it goes in 
    $WIN_INSTALLATION_DRIVE\Documents and Settings\$USER_NAME\Local Settings\Application Data\Local\YourAppName\...

    Yes cross platform makes life difficult, or atleast adds few IF statements. ;)

  2. How to save it: You can save the credentials in JSON file easily. Now as you need the data to be secured and also not read by illegal access, the best way is to encrypt it. NodeJs Crypto module is very easy to use and you can use it in few lines to encry/decrypt your settings file. Your application will only be aware of encryption passwords and hence your application will only be able to decrypt it.

    I would recommend AES-192 for encrypting the files.

Hope it helps!!

like image 144
Kushal Likhi Avatar answered Oct 29 '22 11:10

Kushal Likhi


I found that the yeoman project has a package for this called configstore. I tried it out and the API is incredibly simple and easy to use and abstracts out any need to worry about OS compatibility.

Getting and setting configs is as easy as:

const Configstore = require('configstore')
const config = Configstore(packageName, defaults)
config.set(key, value)
config.get(key)

Yeoman is a large well tested project so the fact that they built and use this in their project should indicate that this is a safe stable package to use in your own project.

like image 35
TimE Avatar answered Oct 29 '22 11:10

TimE