How to require json data to Node.js after bundling the whole server into an executable with the "pkg" compiler?


In normal node.js environment which I run by "npm start", I can always just require/import JSON and the data inside the file will be received.

For an example, if I have "./Assets/port.json" and it includes {"port": 3000}
When I import it and access the data I will get port 3000, and if the data in the port.json file is changed to port:3001, I will then get port 3001 when I import it. Working fine.

But once I package the file using "pkg server.js" and I get my executable, it seems the json data is written to the executable binaries and when I then change the data in the json file to something else, I still get the same data I had in the json file during the compilation of the node.js code into an executable.

How can I prevent the json data from being compiled into the binaries and make the json data be imported once my node.js code is compiled into an executable? It’s really important for me as I am creating a clientside application which will run a server on their LAN, so I must be able to have dynamic ipv4/port imports from the json file possible.


From the pkg doc:

On the other hand, in order to access real file system at run time
(pick up a user’s external javascript plugin, json configuration or
even get a list of user’s directory) you should take process.cwd() or

Code such as:


will automatically be replaced with the loading of a bundled asset in the pkg as that’s what pkg does. It scours your source code for the loading of things using certain rules. If, however, you load it with something like this:

const config = require(path.join(path.dirname(process.execPath), "port.json"));

And make sure that the file port.json is located in the same directory as your packaged executable after your app is installed somewhere, then pkg will leave this code along and allow you dynamically load the config file from the same directory as the executable is located.

Answered By – jfriend00

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published