How to create a node.js app and where to start the newbies often ask these questions. In this article, we’ll try figuring out how it is going on. Node.js app has a few parts. It has always a config file.
The content table:
#Create a config file
We use a config file for put there options for different services like mysql, redis, steam, and other data. You can put there whatever you want they have to be accessible from anywhere of your site and will be edited in one place.
For a config file, we can use YAML it’s a special language that uses for creating configs link.
We will use two npm packages:
The config package will search a config file by following this hierarchy link. We have to create a local.yml file somewhere and specify an environment variable NODE_CONFIG_DIR to this folder. The config will search the file there. To add an environment variable we can use a npm scripts section. Put there this code
“start”: “NODE_CONFIG_DIR=./config node index.js”
it will create add a variable NODE_CONFIG_DIR with a path that you can change whatever you want. The config package will check this path and make search config file. For reading YAML files you have to install js-yaml.
That’s it. Here is a code (To run the code use npm start)
package.json
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
{ "name": "test1", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "start": "NODE_CONFIG_DIR=./config node index.js", "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC", "dependencies": { "config": "^2.0.1", "js-yaml": "^3.12.0" } } |
/config/local.yml
1 2 3 4 5 6 |
APP: PORT: 3000 TITLE: 'Hello world!' MYSQ: HOST: 'localhost' PASS: 'password' |
index.js
1 2 3 |
const Config = require('config'); console.log('Config = ', Config); |
console
1 2 3 4 5 6 7 8 9 |
neo@neo:~/node.js/React/test1$ npm start > test1@1.0.0 start /home/neo/node.js/React/test1 > NODE_CONFIG_DIR=./config node index.js Config = Config { APP: { PORT: 3000, TITLE: 'Hello world!' }, MYSQ: { HOST: 'localhost', PASS: 'password' } } neo@neo:~/node.js/React/test1$ |
the end