pumguard
pumguard

Reputation: 3

I'm trying create a simple module but doesn't work. Node JS

I'm new to Node JS, on this site and English :)) Sorry for all foreign language problems.

Probably I'm getting a "return" error on this codes. When i add the hi.myFunc(); function i'm getting below following error in terminal:

_http_outgoing.js:679
  if (msg.finished) {
          ^

TypeError: Cannot read property 'finished' of undefined
    at write_ (_http_outgoing.js:679:11)
    at write (_http_outgoing.js:661:15)
    at Object.module.exports.myFunc (C:\Users\benom\Desktop\Her Şey\HTML\hi.js:3:9)
    at Server.<anonymous> (C:\Users\benom\Desktop\Her Şey\HTML\app.js:12:16)
    at Server.emit (events.js:315:20)
    at parserOnIncoming (_http_server.js:874:12)
    at HTTPParser.parserOnHeadersComplete (_http_common.js:126:17)

How can i solve this issue?

I got 3 file for this exercise.

app.js

const http = require("http");
const fs = require("fs");
const hi = require("./hi.js");

fs.readFile("./index.html", (err, data) => {
    if (err) {
        throw err;
    } else {
        http.createServer((req, res) => {
            res.writeHead(200, { "Content-Type": "text/html; charset=utf8" });
            res.write(data);
            hi.myFunc(req.url, res.write);
            res.end();
        }).listen(3000);
    };
});

hi.js

module.exports.myFunc = function (url, res) {
    if (url === "/") {
        res("huh");
    };
};

index.html

<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        body {
            background-color: rgba(15, 15, 15, .96);
            color: rgb(255, 255, 255);
        }
    </style>
</head>
<body>

</body>
</html>

Upvotes: 0

Views: 49

Answers (1)

jfriend00
jfriend00

Reputation: 708056

If you want to pass res.write to some other function, you can .bind() the object to it as in:

hi.myFunc(req.url, res.write.bind(res));

Without this, the res object gets lost when you pass it to another function and you end up only with a reference to then .write. Then, when someone tries to call it, it's not called with the proper object and it causes an error.

Upvotes: 1

Related Questions