LCYSoft LCYSoft -4 years ago 153
Node.js Question

How do Browsers load files in library?

I built a node library that loads json files located inside of the lib and does something using the content loaded from json.

so the lib structure is

lib/mylib.js
data/data.json
index.js


in
mylib.js
it does this;

var PATH = path.join(
__dirname,
'../data/data.json'
);

function load() {
return JSON.parse(
fs.readFileSync(
PATH,
'utf8'
)
);
}

module.exports = { load: load};


It works perfectly on server side. I can call
load
function and it shows the contents of json file.
My question is how this works in browsers. I quickly tested on my test server and it worked as well. It printed the contents of the json file on the browser (used chrome and safari).

I have this code in
client.js


import mymodule from 'mylib/lib/mylib';

function MyObject({myobj, styles}) {
return (
<Flex center>
<Spacing push={ {direction: 'ends', size: 'huge'} }>
<h1>{mymodule.load()}</h1>
</Spacing>
</Flex>
);


And this prints the json contents on the browser.
I am not 100% sure how this works though. When browser calls
mymodule.load()
, it looks for the json file in the relative path,
../data/data.json
. How does browser handle the file path? Did server sent the whole lib to browser and browser stored them in some sort of temp storage? Many thanks in advance.

Answer Source

So, a couple things. First, on the server side you can actually do things more simply than you have, if the JSON is static for the life of the application (i.e. w/o restarting). If it's only going to be loaded one time per application start, you can just do this:

// in lib/mylib.js
function load() {
  return require('../data/data.json');
}

I'd actually do it with my other requires, personally, rather than calling a load function, but just wanted to leave it in the function in case you have a good reason for doing so.

On the client, you're going to do one of three things. One, you can set the data folder to public and then call it with an ajax request from the client:

app.use(express.static('./data'));

Two, you can do your own handling of it in an express route, leveraging your myLib functions:

app.get('/data', function(req, res) { return res.send(myLib.load()); });

Three, you could use a build tool like webpack to import the data file using e.g. the json-loader:

https://github.com/webpack-contrib/json-loader

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download