简体   繁体   中英

First argument must be of type string or an instance of buffer or uint8array. Received undefined

I made this code and after everything I try it keeps giving me this error.

First argument must be of type string or an instance of buffer or uint8array. Received undefined

Excuse me for being new at Node.js, but I really don't know where I went wrong. I thank you for your help.

function createServer(obj){
  var i;
  obj.port = (obj.port || 8080);
  obj.path = (obj.path || "/");

  http.createServer((req, res) => {
    res.writeHead(200, {'Content-Type': 'text/html'});
    for(i in obj.path){
      fs.readFile(i, "utf-8", (err, data) => {
        if(err){
          console.log(err);
        }
        res.write(data);
        res.end();
      })
    }
    
  }).listen(obj.port);

  return obj;
}

Your index.js file [https://github.com/notJudahRR/Firwe/blob/main/index.js] set path as an object:

const firwe = require("./src/index.js");

let server = firwe({
  port: 8080,
  path: {
    "/": "index.html"
  },
});
server.initServer();

Then, in server.js [https://github.com/notJudahRR/Firwe/blob/main/src/server.js] you must handle appropriately:

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

function createServer(obj) {
  var i;
  obj.port = obj.port || 8080;
  obj.path = obj.path || {
    "/": "index.html",
  };

  http
    .createServer((req, res) => {
      res.writeHead(200, { "Content-Type": "text/html" });
      Object.values(obj.path).forEach((v) => {
        fs.readFile(v, "utf-8", (err, data) => {
          if (err) {
            console.log(err);
          }
          res.write(data);
          res.end();
        });
      });
    })
    .listen(obj.port);

  return obj;
}

module.exports = createServer;

Object.values loop in each object property value and then you get the index.html to get the file to render.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM