Javascript 在节点JS中添加文件路径

Javascript 在节点JS中添加文件路径,javascript,html,node.js,path,Javascript,Html,Node.js,Path,我们需要在下面的代码中编辑什么才能添加到路径中 我们的路径是app/public。我们希望能够使公用文件夹中的所有文件成为主.html文件。我是新手,任何帮助都将不胜感激! 非常感谢 var http = require("http"), url = require("url"), path = require("path"), fs = require("fs") port = process.argv[2] || 8888; http.createServer(function(reque

我们需要在下面的代码中编辑什么才能添加到路径中

我们的路径是app/public。我们希望能够使公用文件夹中的所有文件成为主.html文件。我是新手,任何帮助都将不胜感激! 非常感谢

var http = require("http"),
url = require("url"),
path = require("path"),
fs = require("fs")
port = process.argv[2] || 8888;

http.createServer(function(request, response) {

var uri = url.parse(request.url).pathname
, filename = path.join(process.cwd(), uri);

path.exists(filename, function(exists) {
if(!exists) {
  response.writeHead(404, {"Content-Type": "text/plain"});
  response.write("404 Not Found\n");
  response.end();
  return;
}

if (fs.statSync(filename).isDirectory()) filename += '/index.html';

fs.readFile(filename, "binary", function(err, file) {
  if(err) {        
    response.writeHead(500, {"Content-Type": "text/plain"});
    response.write(err + "\n");
    response.end();
    return;
  }

  response.writeHead(200);
  response.write(file, "binary");
  response.end();
});
});
}).listen(parseInt(port, 10));

 console.log("Static file server running at\n  => http://localhost:" + port + "/\nCTRL + C to shutdown");

我建议您尝试使用
express
,以使其更易于处理,尤其是在将来应用程序变得更大时

var express = require( 'express' );
var app = express( );
var cookieParser = require('cookie-parser'); // might be useful. Not required though

app.set( 'port' , process.argv[2] || 8888 );
app.use( express.static( './public' ) ).use( cookieParser( ) ); // sets path to your public folder

// you can add some more configuration here

// then finally start your server
http.createServer( app ).listen( 
    app.get( 'port' ) ,
    function( ) {
        console.log( 'Express server listening on http port ' + app
                .get( 'port' ) );
        // here, complete with your callback
    } 
);

以下是明确的文档:

为什么我的答案中出现了-1?