Home > Enterprise >  How to require json data to Node.js after bundling the whole server into an executable with the &quo
How to require json data to Node.js after bundling the whole server into an executable with the &quo

Time:08-20

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.

CodePudding user response:

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 path.dirname(process.execPath).

Code such as:

require("./Assets/port.json")

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"));
console.log(config.port);

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.

  • Related