In Nuxt server api, I want to import a static json file, from the assets folder, with a dynamic name
export default defineEventHandler(async (event) => {
const query = getQuery(event)
const path = query.path as keyof typeof FilePaths
enum FilePaths {
"home" = "../../assets/json/home.json",
"article-1" = "../../assets/json/article-1.json",
"article-2" = "../../assets/json/article-2.json",
"article-3" = "../../assets/json/article-3.json",
"article-4" = "../../assets/json/article-4.json",
"article-5" = "../../assets/json/article-5.json",
"article-6" = "../../assets/json/article-6.json",
}
const filePath = FilePaths[path]
const page = await import(filePath, { assert: { type: 'json' } })
})
And I get this error
[nuxt] [request error] [unhandled] [500] Module "file:///D:/folder/assets/json/article-1.json" needs an import assertion of type "json"
It works if I pass the hardcoded string
await import("../../assets/json/article-1.json")
But don't work with a variable, or a concatenated string
How can I do it dynamically? I don't want to import all of the files, or hardcode them paths
I tried:
- specify possible filenames
- add assert option as error says
I've managed it by using fs.readFile
Is there a better solution?