-
I have a file I need to load data from and use it in I managed to do it with using Is there a way to make it read the file once only upon server startup, and then use that data throughout the lifetime of the application? A. la. putting the values into Note: using environment variables instead of a file is not an option. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
If it's a JSON file, you can import it directly, but you should do it from a *.server file so the file doesn't get bundled with the client. However, if you need to load a regular file, here's a pattern that should work. // app/data/getData.server.ts
import * as fs from "fs";
let data: string;
declare global {
var __data__: string;
}
// store data on global in development mode
// to survive purge of require cache
if (process.env.NODE_ENV === "production") {
data = readData();
} else {
if (!global.__data__) {
global.__data__ = readData();
}
data = global.__data__;
}
function readData() {
let contents = fs.readFileSync(`${process.cwd()}/app/data/data.json`, "utf8");
return JSON.parse(contents);
}
export function getData() {
return data;
} // app/routes/root.tsx
import { getData } from "~/data/getData.server";
export const loader = async () => {
const data = getData();
const user = data[0];
return json({ user });
}; |
Beta Was this translation helpful? Give feedback.
If it's a JSON file, you can import it directly, but you should do it from a *.server file so the file doesn't get bundled with the client.
However, if you need to load a regular file, here's a pattern that should work.