Next.js Discord

Discord Forum

How to get correct path to file included with asset/resource?

Unanswered
Atlantic mackerel posted this in #help-forum
Open in Discord
Atlantic mackerelOP
I have a CSV file inside my src folder that I'm trying to access server-side. I set up webpack with the following rule:
    config.module.rules.push({
      test: /\.csv$/,
      type: 'asset/resource',
    });


When I go to import the file, I am doing this:

import policyFile from "./casbin/policy_data.csv";


This gives me the pathname: "static/media/policy_data.09e1c3ae.csv"

However, when I go to open this file, I get:

ENOENT: no such file or directory, open 'static/media/policy_data.09e1c3ae.csv'

There are actually two folders missing in this path - relative to the CWD, the file is actually located at "build/server/chunks/static/media/policy_data.09e1c3ae.csv".

Of course, running in development mode, it's not at "build/server/chunks", it's at a different path.

How do I get the FULL PATH to the file at runtime, regardless of whether it's a dev or production build?

9 Replies

Idk about via webpack
But using fs.readFileSync
path.resolve(process.cwd(), “src”, “yourfile.csv”)
The key is using process.cwd() otherwise the path isn’t built correctly when deployed to prod (at least on vercel)
@Atlantic mackerel ^
Atlantic mackerelOP
yeah unfortunately process.cwd wasn't the full first portion of the path
I ended up adding this to the config which worked:
the generator doesn't actually do anything but somehow including it this way, I get the same path in both directions