繁体   English   中英

第一个参数必须是字符串类型或缓冲区或 uint8array 的实例。 收到未定义

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

我制作了这段代码,在我尝试了一切之后,它一直给我这个错误。

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

对不起,我是 Node.js 的新手,但我真的不知道我哪里出错了。 我感谢你的帮助。

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;
}

您的 index.js 文件 [https://github.com/notJudahRR/Firwe/blob/main/index.js] 将路径设置为 object:

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

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

然后,在 server.js [https://github.com/notJudahRR/Firwe/blob/main/src/server.js] 中,您必须正确处理:

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 在每个 object 属性值中循环,然后获取index.html以获取要渲染的文件。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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