Search code examples
node.jszeit-pkg

Make node script packaged with zeit-pkg aware of full filesystem


I have a node script which uses command line parameters using the module commander.

I want to pack it with pkg, but I am running into some trouble.

Normally I would execute my script with:

node index.js --file ./test.csv

but the file argument could point to any folder in the user's filesystem.

I have looked into configuring the assets and scripts attributes for pkg in package.json, but it looks like you need to specify a folder in there, such as:

"pkg": {
    "scripts": "build/**/*.js",
    "assets": "views/**/*"
  }

How can I make a zeit-pkg packged node script aware of any possible location in the filesystem?

I am simply building with pkg package.json , since in package.json I have the entry:

"bin" : "index.js"

Solution

  • In your pkg-packed source, add this in the beginning:

    console.log("process.cwd() = " + process.cwd());
    

    When you run your packaged exe this will tell you what your executable sees as its working directory. You can then interpret any relative arg-paths of your application (like "./index.csv") relative to that.

    It seems based on my experiments that pkg-applications have full access to the file-system as long as your program knows the absolute paths of the files you want to read or write or even "require".

    The only tricky thing seems to be relative paths. The reason is that pkg wants you to be able to package resource/asset -files into the executable and then access them like you would any file at runtime. That is actually a great feature but often more than you need.

    If you don't need to package any (extra) files into your executable then file-system access should be simple and work just normally with absolute paths. You just need to know "where you are" if you want to use relative paths.

    I'm not affiliated with the pkg project so my answer is not authoritative in any way. I hope zeit would put more documentation about the file-system access into their site, especially cross-platform. After doing some experimentation myself it just seems accessing files by their absolute paths works, on Windows.