0

I'm building a small program using nodejs that I plan to add as a sort of backend service to an expressJS webserver that I am still yet to develop.

Not wanting to have the whole program on display in the webserver itself, I've read that compiling node project is possible, which seemed like the solution.

Here's the thing: as of right now, whenever I run my index.js, the program performs some tasks and eventually some changes to json files.

I want to keep these changes on the json files for when the program is called once again, the json will remain in the same state as the last execution left it.

Is this the default behaviour? Am I doing something incorrectly?

Thank you.

Ress
  • 77
  • 13

2 Answers2

0

It's not completely clear what you want, but

  • Node runs javascript, if your program is written in javascript, it can run it, no need to compile it. You might need to compile it if you're using a compile-to-JS language like TypeScript, but Node understands JavaScript directly. You might need transpile it if you're using import/export on an old version of Node, more here

  • using require('./your/file.json') will keep the content in the require cache and will be the same for the whole duration of the program, even if you write newer content to the file, but JSON.parse(fs.readFileSync('./your/file.json')) will fetch the latest version of it everytime.

  • If by "compiling" you mean compiling to an executable, I would strongly recommend against that. You'll lose the stack trace, decrease speed, increase your program size, etc. You should instead wrap your node program inside a package, which basically means having a package.json at the root of your node program with at least the fields name, version and main.

Nino Filiu
  • 16,660
  • 11
  • 54
  • 84
  • Thank you for the answer. What I meant with compiling is that I'm basically going to have to do a node project (my custom node program) inside another node project (the expressJS webserver), and to avoid doing so (and hide the program's functionality as well) I was considering compiling my custom program, like so: https://www.section.io/engineering-education/compile-your-nodejs-application-into-a-exe-file/. Does that even make sense? I'm a bit new to node. Almost like a library in Java that I can call whenever, if you will. – Ress Aug 17 '21 at 16:29
0

I want to keep these changes on the json files for when the program is called once again, the json will remain in the same state as the last execution left it.

In order to persist the changes between executions, you need to write the changes to disk.

Not wanting to have the whole program on display in the webserver itself, I've read that compiling node project is possible, which seemed like the solution.

If you want to hide the logic of your javascript code from the webserver, your best bet is to convert your javascript code to an api, so that the other webserver just calls this new api, get the results and persist them to disk.