我们需要在以下代码中编辑哪些内容才能添加到路径中?
我们的路径是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");
答案 0 :(得分:-1)
我建议您尝试使用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
}
);
这是Express文档:http://expressjs.com/