0

这是我的代码

   //Require modules
var http = require("http");
var url = require("url");
var path = require("path");
var fs = require("fs");

var mimeTypes = {
  html: "text/html",
  jpeg: "image/jpeg",
  png: "image/png",
  jpg: "image/jpg",
  js: "text/javascript",
  css: "text/css",
};

http
  .createServer(function (req, res) {
    var uri = url.parse(req.url).pathname;
    var fileName = path.join(process.cwd, unescape(uri));
    console.log("Loading " + uri);
    var stats;

    try {
      stats = fs.lstatSync(fileName);
    } catch (error) {
      res.writeHead(404, { "Content-type": "text/plain" });
      res.write("404 not Found");
      res.end();
      return;
    }
    if (stats.isFile()) {
      var mimeType = mimeTypes[path.extname(fileName).split(".").reverse()[0]];
      res.writeHead(200, { "Content-type": mimeType });

      var fileStream = fs.createReadStream(fileName);
      fileStream.pipe(res);
    } else if (stats.isDirectory) {
      res.writeHead(302, { location: "index.html" });
      res.end();
    } else {
      res.writeHead(500, { "Content-Type": "text/plain" });
      res.write("500 Internal Error");
      res.end();
    }
  })
  .listen(3000);

这是在终端中查看的错误:

> simpleserver@1.0.0 start C:\Users\User\Desktop\Codes\html workspace\node_temp\simpleserver
> node server.js

internal/validators.js:120
    throw new ERR_INVALID_ARG_TYPE(name, 'string', value);
    ^

TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received function wrappedCwd
    at validateString (internal/validators.js:120:11)
    at Object.join (path.js:375:7)
    at Server.<anonymous> (C:\Users\User\Desktop\Codes\html workspace\node_temp\simpleserver\server.js:20:25)
    at Server.emit (events.js:315:20)
    at parserOnIncoming (_http_server.js:790:12)
    at HTTPParser.parserOnHeadersComplete (_http_common.js:119:17) {
  code: 'ERR_INVALID_ARG_TYPE'
}
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! simpleserver@1.0.0 start: `node server.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the simpleserver@1.0.0 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm WARN Local package.json exists, but node_modules missing, did you mean to install?

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\User\AppData\Roaming\npm-cache\_logs\2020-10-19T13_55_19_012Z-debug.log

我是 nodeJS 的新手,我正在从 youtube 教程中学习。我也创建了 index.html 页面。我正在尝试在“http://127.0.0.1:3000/index.html”上运行 index.html 页面。我做了他们所做的。我重新检查了任何错误。请帮助我...在此先感谢

4

1 回答 1

1

更改process.cwdprocess.cwd()。您正在使用旧版本 node.js 的语法。这是当前的API 参考

于 2020-10-19T14:18:00.063 回答