Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define path prefix in ServeStaticModule?

Tags:

nestjs

I want to serve some static directory structure according to this docs https://docs.nestjs.com/recipes/serve-static#serve-static but can find answers to these simple questions:

  1. How to set up path prefix like '/some/path/to/files'?
  2. How to set up serving at runtime (files path is dynamic and can't be hardcoded)?

Thanks in advance.

P.S. I saw some answers about app.useStaticAssets() but as far as I understood this is Express specific solution and wont compile with latest version anyway (Property 'useStaticAssets' does not exist on type 'INestApplication')...

Update

For example I have these diractories:

  1. /var/lib/app/data1
  2. /var/lib/app/data2
  3. /home/user/some/path

And I want it to be served as:

  1. http://localhost:3000/path1
  2. http://localhost:3000/path333
  3. http://localhost:3000/my/funny/cats
like image 486
Dimanoid Avatar asked Jan 20 '20 20:01

Dimanoid


3 Answers

This is an old question but I encountered it for the same problem.

Here is mine, so with the help of the answer of @Jay, which gives the link to all the options available on github, I was able to find the correct option, which is serveRoot when using NestJS ServeStaticModule.

Here is the use case where I used it :

ServeStaticModule.forRoot({rootPath: '/media/avatar', serveRoot: '/avatar'})

This line above is to include in your app.module in the import, basically I'm saying that files located in /media/avatar should be served on localhost:1234/avatar.

like image 147
HartWoom Avatar answered Oct 29 '22 00:10

HartWoom


You asked

How this can help me to serve many different folders from the different paths and some of them should be determined at runtime?

You can have several ServeRoot declarations, like so:

ServeStaticModule.forRoot({
  serveRoot: '/path1',
  rootPath: `/var/lib/app/data1`,
}),
ServeStaticModule.forRoot({
  serveRoot: '/path333',
  rootPath: `/var/lib/app/data2`,
}),
ServeStaticModule.forRoot({
  serveRoot: '/my/funny/cats',
  rootPath: `/home/user/some/path`,
}),

as for "determined at runtime", maybe a ServeStaticModule can not do this. Others should please correct me on that.

like image 30
serv-inc Avatar answered Oct 28 '22 23:10

serv-inc


You can set the renderPath options on the ServeStaticModule. Normally the path is '*' so anything that doesn't match your other defined routes attempts to get sent via res.sendFile(). If you want to make it some/path/to/file you can set renderPath: 'some/path/to/files/* and it should work out.

like image 1
Jay McDoniel Avatar answered Oct 28 '22 23:10

Jay McDoniel