【问题标题】:Add File Path in NODE JS在 NODE JS 中添加文件路径
【发布时间】:2016-07-25 12:21:44
【问题描述】:

我们需要在以下代码中编辑什么以添加到我们的路径中?

我们的路径是 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");

【问题讨论】:

  • 为什么我的答案是-1?

标签: javascript html node.js path


【解决方案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/

【讨论】:

    猜你喜欢
    • 2013-06-16
    • 2015-08-14
    • 1970-01-01
    • 2013-08-22
    • 2020-04-17
    • 1970-01-01
    • 1970-01-01
    • 2012-11-17
    • 1970-01-01
    相关资源
    最近更新 更多