0

I'm trying to reuse/call function but with one additional parameter in the middle

const fs = require('fs');

module.exports = (filePath, res) => {
fs.readFile(filePath, (err, data) => {

    if (err) {
        console.log(err);

        res.writeHead(404, {
            'Content-Type': 'text/plain'
        });
        res.write('Page not found!');
        res.end();
        return;
    }

    res.writeHead(200, {
        'Content-Type': 'text/html'
    })
    res.write(data);
    res.end();
})
}

In next case I have to add additional parameter when reading file.

fs.readFile(filePath, utf-8, (callback) => {})...

Is it possible to make new function with bind or call it with an additional argument in my case is in the middle I need to add encoding utf-8 without modifying the function because is wrapped as module. Or perhaps I need to change the function to work with two or three parameters. In short my goal is using the same function with minor changes because it's 90 % the same.

EDIT:

I need to use the same function for reading file but this time needs to add encoding. So instead of fs.readFile(filePath, (callback) => {})

should be fs.readFile(filePath, 'UTF-8', (callback) => {})

You can see what I'm trying to do in github. This is the file for serving static files

https://github.com/xakepa/SoftUni/blob/Beta/JS%20WEB/Node%20JS/Cat%20Shelter/handlers/static-files.js

This is the function I'm trying to reuse

https://github.com/xakepa/SoftUni/blob/Beta/JS%20WEB/Node%20JS/Cat%20Shelter/handlers/readHtml.js

Simba
  • 303
  • 1
  • 4
  • 17
  • Does this answer your question? [Function overloading in Javascript - Best practices](https://stackoverflow.com/questions/456177/function-overloading-in-javascript-best-practices) – Rodentman87 May 25 '20 at 18:22
  • You said send parameter `in the middle` is it important? or you can send it at the last param . – Dupinder Singh May 25 '20 at 18:22
  • One way is to send the `JSON` object in the function parameter and extract your required parameters from `JSON` while execution of function – Dupinder Singh May 25 '20 at 18:26
  • What do you mean by "*without modifying the function*"? – Bergi May 25 '20 at 18:31
  • You can use function curry as well, create two functions with different parameters. – Amir Saleem May 25 '20 at 18:31
  • 1
    Btw, it's much more likely that you actually just want to [fix the `Content-Type` header to say `"text/html;charset=utf-8"`](https://www.w3.org/International/articles/http-charset/index), not read the file as an utf-8 string. – Bergi May 25 '20 at 18:33
  • Thank you. I added function getContentType to get the proper type and when is HTML I added the encoding. – Simba May 26 '20 at 08:52

0 Answers0