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:
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:
And I want it to be served as:
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
.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With