1
\$\begingroup\$

My starting point is a file like so:

# Default environment to run the app locally.
# In production, the app will probably run on NginX,
# which will act as a reverse proxy
export NODE_ENV='development'
export APPNAME='gigsnet'
export DBHOST='192.168.1.13'
export DBNAME='gigsnet-development'
export IPADDRESS='localhost'
export PORT='8080'

This is a simple bash file that sets and exports some environment variables. I want some nodeJs scripts to use the same file to set the same variables. The idea is to require this file, and have process.env magically enriched.

So, I wrote this:

var fs = require('fs')
var p = require('path')
fs.readFileSync(p.join(__dirname, 'localEnv.sh')).toString().split('\n').forEach(line => {
 var tokens = line.split(' ')
 if (tokens[0] === 'export') {
 var [ name, value ] = tokens[1].split('=')
 process.env[name] = value.match(/["'](.*?)["']/)[1]
 }
})

Problems I have:

  • That first line is way too long for my own likings
  • The variable token could and should have a better name

Looks clunky.

How would you improve it?

asked Dec 19, 2017 at 14:07
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$
  • The fact that you're parsing BASH means you're probably not worried about portability, which means you probably don't need the path module since the directory separator will always be /. So, you can replace p.join(__dirname, 'localEnv.sh') with __dirname+'/localEnv.sh'
  • There's a module for reading stuff line by line already, no need to home-roll it.
  • This is a better regex because it takes escaped quotes into account: "(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*' see here.

require('readline').createInterface({
 input: require('fs').createReadStream(__dirname+'/localEnv.sh')
}).on('line', function (line) {
 var tokens = line.split(' ')
 if (tokens[0] === 'export') {
 var [ name, value ] = tokens[1].split('=')
 process.env[name] = value.match(/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'/)[1]
 }
});
answered Dec 19, 2017 at 15:02
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.