Scan a list of assigns in nodejs 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 =&gt; {
  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?
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]
  }
});