Polka: improve documentation about loading the public folder and read posts requests

Created on 9 Oct 2019  ·  11Comments  ·  Source: lukeed/polka

First of all a big thank you for Polka 💯 is always nice to have some diversity in the node ecosystem and this is really nice.

I think the documentation could use some improvements on how to load a /public folder.
I appreciate that there is an example to use serve-static (https://github.com/lukeed/polka/blob/master/examples/with-serve-static/index.js) but I just can't figure out how would you load e.g. a CSS file? I did try it and didn't work for me.

So I did write this which I assume to be not the right way to do things but it works.

app.get('/public/:file', (req, res) => {

    console.log(req.params);
    if (fs.existsSync('./public/' + req.params.file)) {

        var file = fs.readFileSync('./public/' + req.params.file, 'utf8');
        res.write(file);
        res.end();

    } else {
        res.writeHead(200, {
            "Content-Type": "text/html; charset=utf-8"
        });
        res.write("⚽⚽⚽⚽ 404 - not found ⚽⚽⚽⚽");
        console.log(req);
        res.end('error')
        console.log(req.params);

    }

});

would serve-static provide a better approach to this ?

I believe that at least two elements have to be very clear in the readme/docs (without having to dig through all the example)
a) how to parse post requests e.g. the current example just deal with JSON but I figured it out how to do it for forms too

app.use (bodyParser.urlencoded({ extended: true }));

b) how to load a public folder
c) how to use templates (thanks to the good soul that provided polka-ejs!)

I understand that most people will use polka as a backend/API but why capture the rest of the audience too ? :) with EJS all is working very fine!

question

Most helpful comment

Does polka have built-in method to send html file? Something similar in express:

app.get("/contact", (req, res) => {
  return res.sendFile(path.join(__dirname, "../landing_page/contact.html"));
});

All 11 comments

Hey, thank you :)

Yes, serve-static or sirv are meant for this. If you go down this route, you end up reimplementing the same logic anyway. What you have is the _bare bones_ logic, but it doesn't account for the many behaviors that need to be implemented (streaming, chunk encoding, etc)

In the example, you'd point this line to your public directory. Then, here, it's attaching the entire middleware to your base application. This means that a request for /bundle.min.css will look for the ./public/bundle.min.css file.

However, judging by this issue, it seems like you want to keep the /public/ segment in your URL request. If that's the case, then it'd look like this:


const { join } = require('path');
const polka = require('polka');

const { PORT=3000 } = process.env;

const dir = join(__dirname, 'public');
const serve = require('serve-static')(dir);

polka()
    .use('/public', serve)
    // ...

With this, the request to /public/bundle.min.css will serve the bundle.min.css file inside your public folder. However, a request to /bundle.min.css will fail (404) since it doesn't begin with "/public" – which means Polka won't invoke the serve middleware.

Hope that helps!

thanks a lot @lukeed this was very helpful 👍 works fine with serve-static! I also tried the sirv example but no luck: nothing is loaded out of /public

I now have

const sirv = require('sirv');
const compress = require('compression')();

const assets = sirv('public', {
  maxAge: 31536000, // 1Y
  immutable: true
});


app.use(ejs()); // load ejs for templating 
app.use (compress, assets)

I wonder if I miss to pass a parameter to polka or something like telling which route to use sirv with ..

Thanks again!

Great!

You can send me a link to what you have and I will take a look. They work nearly identical to one another, so there shouldn't be a problem like that

Thanks again for your help! It works fine with body parser but not with sirv.
It is probably something small I forgot but here are the 2 versions
https://gist.github.com/gurugeek/72419256462baf32d38906256cc23c32

They're configured differently:

const dir = join(__dirname, 'public'); //loading public folder 
const serve = require('serve-static')(dir);
app.use('/public', serve);

// vs

const sirv = require('sirv');
const assets = sirv('public', {
  maxAge: 31536000, // 1Y
  immutable: true
});
app.use (compress,assets);

If you want the sirv usage to be the same, this is what you need:

const dir = join(__dirname, 'public');
const serve = require('sirv')(dir); // <~ HERE
app.use('/public', serve);

The options you provided don't change anything in relation to this. You can add them back in and it'll keep working.

thanks a loot! apparently I did a mistake by commenting the const dir in the sirv version
with you latest example all works fine so I don't really need
const assets = sirv('public', {
maxAge: 31536000, // 1Y
immutable: true
});

right ?

Cool. That's just a different way to configure the same thing.

  • The join(__dirname, 'public') is just a more explicit/direct way to point to the public dir.
  • The options you provided can be used in my example, too

The main difference was that you weren't doing .use('/public', ...) which meant that previously, your requests to /public/file.js was being searched at ./public/public/file.js.

Here's complete example, using options:

```js
const dir = join(__dirname, 'public');
const serve = require('sirv')(dir, {
maxAge: 31536000, // 1Y
immutable: true
});

app.use('/public', serve);

awesome !
does it means that without the options of maxAge it wouldn't be using caching ?
Also in this new application I don't use or include compression. Is that needed for files for instance ?
Sorry for the many questions and thanks again. I like that I can now use Polka with sirv!

Please refer to the sirv documentation

will do, much appreciated!! thanks again for your wonderful framework and libraries.

Does polka have built-in method to send html file? Something similar in express:

app.get("/contact", (req, res) => {
  return res.sendFile(path.join(__dirname, "../landing_page/contact.html"));
});
Was this page helpful?
0 / 5 - 0 ratings

Related issues

flawyte picture flawyte  ·  7Comments

motss picture motss  ·  4Comments

fanatid picture fanatid  ·  5Comments

itaditya picture itaditya  ·  3Comments

ansarizafar picture ansarizafar  ·  3Comments