Assuming you are using Express you can use the express function. static () that serves just to "serve static files".
This function has the following structure:
express.static(root, [options])
You can use the __dirname
native function to reference the folder itself as relative path and thus be able to concatenate with the rest of the path to your folder when it is at or above levels.
The following example assumes that your project has the following folder structure:
root folder
|
|---- render
| |
| |---- views
|
|---- node_modules
// todo conteúdo da pasta views disponível via GET
app.use(express.static(__dirname + '/render/views'))
This function allows all files in the selected folder and all the underlying directories to be available through a GET
request.
It also allows (optionally) to set options such as: etag
, maxAge
, list of extensions, set headers
or even whether directory browsing is allowed or not ... this is an example of options of the function in the documentation itself:
var options = {
dotfiles: 'ignore',
etag: false,
extensions: ['htm', 'html'],
index: false,
maxAge: '1d',
redirect: false,
setHeaders: function (res, path, stat) {
res.set('x-timestamp', Date.now())
}
}
app.use(express.static('public', options))
If you do not want to make all the contents of the directory available, you can simply treat one or more specific files via routing by the% example request:
const fs = require('fs')
// ...
app.get('/index.ejs', (req, res, next) => {
res.type('text/plain')
.send(fs.readFileSync('./render/views/index.ejs', 'utf-8'))
.end()
})
By routing it is important to set the GET
suitable ... as "templates" mime-type
are not equal to files .ejs
should only use .js
.
Using this method it is possible to serve any type of file, just add the text/plain
correct.
In your Service Worker would look something like:
self.addEventListener('install', function(event) {
event.waitUntil(
caches.open(CACHE_NAME).then(function(cache) {
return cache.addAll([
'/',
'/index.ejs',
'../css/materialize.css',
'../css/custom.css', ....
Without having to go back or forward directories in the path declaration of the file mime-type
.
Try it and say it worked out.
Source: Express 4.x API