Jeremy Foster Jeremy Foster - 10 months ago 59
Node.js Question

How to package assets with a node module

I'm trying to include some simulation data with a node module (module B) and then be able to reference that data from the calling module (module A). The data is a text file in the

directory of module B. I have a function on module B that calls up the data using __dirname, but of course when this function is called from module A, the __dirname references the directory of module A... not module B.
What's the best way to include asset data like this and make it available in the consuming module?


When packaging a module you can use the files property of package.json to bundle any assets along with your module.

Then, in that module, you can use a relative path to reference your included asset.

Imagine a module with this file structure:


In your package.json you might have a files section that looked like:

files: [

And in index.js you could expose your asset data like so:

let fs = import 'fs';

function getAssetData() {
   return fs.readFileSync('./assets/data.txt')

module.exports = { getAssetData };