-
The code below is to send the main.js file from the server on request. And I have to write something like that for every single file that the client requests. Is there a way to do it more efficiently? uwss.get('/public/js/main.js', (res, req) => {
var data = fs.readFileSync(__dirname + '/public/js/main.js');
if(data){
res.write(data);
}
res.end();
}); |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 2 replies
-
In the user manual and in examples you can see the use of parameter routes. /public/js/:filename Where you can do let filename = req.getParameter(0); |
Beta Was this translation helpful? Give feedback.
-
Thanks! But what if I want to put all the parameters? Potentially allowing all folders and files in the /public folder to be accessible. All I can think is: uwss.get('/public/:a/:b', (res, req) => {
var data = fs.readFileSync(__dirname + '/public/' + req.getParameter(0) + '/' + req.getParameter(1) + '/' + req.getParameter(2))...etc. ;
if(data){
res.write(data);
}
res.end();
}); |
Beta Was this translation helpful? Give feedback.
-
you dont want to use readFileSync though you want the async version readFile app.get('/public/*',(res,req)=>{
res.onAborted(()=>res.ab=true)
fs.readFile(__dirname+req.getUrl(),(err,data)=>{
if(res.ab)return
if(err)return res.writeStatus('404').end()
res.end(data)
})
}) I dont use readFile in my apps per request, I load files once into JS memory on server start and then watch them for changes, but I dont have a huge amount of files. if you have large files use fs.createReadStream |
Beta Was this translation helpful? Give feedback.
In the user manual and in examples you can see the use of parameter routes.
/public/js/:filename
Where you can do
let filename = req.getParameter(0);