Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a config file for node pkg

I use node pkg to create a .exe of my nodejs service: https://www.npmjs.com/package/pkg

My question is: how do I make the .exe use a config.js for some setup values? Basic stuff like ip, port, database name etc. Because I have 3 environments, and I would like to use the same exe for all, but different config.js files for each.

So far, if I do pkg app.js then it creates an .exe that doesn't look at any other files. Totally stand alone. How do I make it look at config.js when it is started up?

On the website they do have a section on config https://github.com/zeit/pkg#config but I do not understand how to make use of it. At the moment I have my app.js, and I have secrets.js which holds the config information.

like image 605
Paul Kruger Avatar asked Oct 20 '25 09:10

Paul Kruger


2 Answers

I am not sure this is right way, but I hope this can be helpful to somebody.
Refer to pkg document, on the run time, __dirname becomes "/snapshot/project".

So, by checking __dirname, you can identify in which environment you are.
(node app.js or app.exe).

Then we can separate require sentence like below.

const PKG_TOP_DIR = 'snapshot';

const runInPKG = (function(){
  const pathParsed = path.parse(__dirname);
  const root = pathParsed.root;
  const dir = pathParsed.dir;
  const firstDepth = path.relative(root, dir).split(path.sep)[0];
  return (firstDepth === PKG_TOP_DIR)
})();

let config = require('./appconfig.json');

if(runInPKG) {
  const deployPath = path.dirname(process.execPath);
  config = require(path.join(deployPath, 'appconfig.json'));
}
  • Adding above code to your app.js makes some warning when pkg build.

pkg . --targets node8-win-x64 --out-path ./dist

[email protected] Warning Cannot resolve 'path.join(deployPath, 'appconfig.json')'
app.js
Dynamic require may fail at run time, because the requested file
is unknown at compilation time and not included into executable.
Use a string literal as an argument for 'require', or leave it
as is and specify the resolved file name in 'scripts' option.

like image 120
ryuken73 Avatar answered Oct 21 '25 23:10

ryuken73


https://github.com/vercel/pkg/issues/195
use fs to read config file insead of require or import
eg:
const configPath = path.join(process.cwd(), './config/config.json');
lset data = fs.readFileSync(configPath);

same question link:excluding config file while converting node js files to exe using pkg

like image 30
cszhjj Avatar answered Oct 22 '25 01:10

cszhjj



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!