Search code examples
javascriptnode.jswindow

How to convert a vanilla node server into a executable?


I want to make a node .exe file that runs in the background.

I'm not using third npm packages, but the server is using these modules:

  • FS (File System)
  • Exec (Child Process)
  • HTTP (Server)

The Exec triggers a batch file that opens a console.exe program.

Is there a way to bundle this up into a single .exe?


Solution

  • There is an npm package called pkg. You can install it with

    npm i pkg -g
    

    Then you can convert your node project into an exe (macos and linux too) using:

    pkg (yourfile).js
    

    You can put the batch file with your packaged node exe to run it.

    EDIT:

    I misunderstood the question before, but to do this, you need to use a generator file. Unfourtunately it wont work for your binary files, but if you want use text files, you can do something like:

    Create a file structure like this:

    src/
      generator/
        generate.js
      asset.txt
      app.js
      makefile
    

    in your makefile, put

    .PHONY: all
    all:
      node generator/generate.js
      pkg app.js
    

    and in generate.js you can have something like:

    fs.readFile("asset.txt", (e, data) => {
      fs.writeFile("assets.js", `
        var asset_txt = \`${data}\`
      `);
    });
    

    and in your app.js, require the assets.js file. It may be a messy solution, but I don't think there is a really good way.