How can I serve static file using @nrwl/express

Viewed 257

I am using nx to manage my work environment with @nrwl/express plugin. I want to serve static file from the express server but with no success.

I tried the following.

express.static(path.join(__dirname, 'videos'));

but I am not able to get the files inside the videos directory, I always get 404.

I tried both this URLs http://localhost:3333/api/output.m3u8

http://localhost:3333/output.m3u8

the videos directory is located in the root of my app.

Any idea how can I solve this?

2 Answers

Not sure if you ever solved this but I've just ran into the same problem myself.

When you serve your Express App with Nx it will be transpiled and served from the dist folder. Therefore __dirname will actually resolve to your monoreporoot/dist folder (i.e. the root of your project /dist).

If like me you were trying to serve content from a static folder inside your src directory or similar, you will need to ensure that it's transferred across to your dist folder when serving your Express app.

For me, it wasn't a problem as I was just using it as a temporary upload folder for dev so I manually created the folder inside of dist. If it's linked to your app then you might need to add a specific mkdir or cp command to your build to make sure the files/folder is present.

The process of using from the dist folder, so it is necessary that the source folder be copied.

Add a line to project.json

{
  "targets": {
    "build": {
      "executor": "@nrwl/node:webpack",
      "outputs": ["{options.outputPath}"],
      "options": {
        ...
        "assets": ["packages/<your-app>/src/public"] <-- need add this line
      },
      "configurations": {
        ...
      }
    }
}

Add this in your main.ts

app.use('/static', express.static(__dirname + '/public'));

The file in packages/[your-app]/src/public/some-file.txt will be available at

http://localhost:3333/static/some-file.txt
Related