Home > Software design >  nodejs server - how to load file in memory to use in Modules
nodejs server - how to load file in memory to use in Modules

Time:01-27

Good Morning Everyone,

First, I am not a full dev, this is a hobby, I'm using a NodeJS / ExpressJS server (in ES6) to serve an application I made for 2000 people. This was all reversed engineered. But I am in a rush to fix the app, as the normal API point I was using is now going down, I had to rewrite loads of things.

The last thing I need to fix most problems I have; I am using 2 JSON files that contains about 50MB data each. Obviously I don't want to load those everytime in memory.

The way I wrote my code, I'm using server.js to load all my API points that people can call. Then I broke my functions withing Modules (files in different folders) to keep things clean.

Here are the questions.

  1. Can I load those 2 files in Memory and access them from my Modules, if so how?
  2. Removed my second question for update file - Will do it differently then with nodejs

As it was counter productive to try and make it work when I have another solution

CodePudding user response:

You can use the following to delete the file from the memory management

delete require.cache[require.resolve('FILE')];

CodePudding user response:

Hi pSyToR if you can load your json files and then export them both. other files can then import them and edit the values on them if needed, you can also use globalThis to make them globally available

I have an example below of both

via exports

import * as fs from 'fs'

const fileA = JSON.parse(fs.readFileSync('fileA.json', { encoding: 'ascii' }))
const fileB = JSON.parse(fs.readFileSync('fileB.json', { encoding: 'ascii' }))

export { fileA, fileB }

Importing

import { fileA, fileB } from 'path/to/file-handler.js'

via globalThis

import * as fs from 'fs'

const fileA = JSON.parse(fs.readFileSync('fileA.json', { encoding: 'ascii' }))
const fileB = JSON.parse(fs.readFileSync('fileB.json', { encoding: 'ascii' }))

globalThis.fileA = fileA
globalThis.fileB = fileB

Importing

var data = globalThis.fileA.data

hope this helps.

  • Related