簡體   English   中英

使用Node.js提供JavaScript文件

[英]Serving Up a Javascript file using Node.js

我正在嘗試使用一個非常基礎的node.js服務器提供一些靜態文件。 目的是為HTML文件提供帶有引用JavaScript文件的腳本標簽。 在瀏覽器中打開應用程序時,html呈現良好,問題出在js文件上。 在瀏覽器中,js文件中包含html代碼,而不包含js代碼。

服務器代碼:

var http = require('http')
var fs = require('fs')

var port = 3000;

var app = http.createServer(function(req, res){
    var html = fs.createReadStream('./index.html')

    html.pipe(res);
})

app.listen(port, function(){
    console.log('Listening on port ' + port)
})

HTML CODE(index.html):

<!DOCTYPE html>
<html>
 <head>
  <meta charset="utf-8">
  <title>Hello</title>
 </head>
 <body>
  <h1>Hello</h1>
  <script src="./some.js"></script>
 </body>
</html>

JAVASCRIPT CODE(some.js):

console.log("Hello")

目錄結構:

|-index.html
|-some.js
|-app.js(server)

我建議您以以下方式為需要服務的文件創建目錄

|-public
    |-index.html
    |-some.js
|-app.js(server)

然后,您使用express.static來服務您創建的目錄。

var express = require('express');
var app = express();
var path = require('path');
var port = 3000;

app.use(express.static(path.join(__dirname, 'public')));

app.listen(port, function(){
   console.log('Listening on port ' + port)
})

那你就跑

node app.js

不使用快遞,您可以執行以下操作

var http = require('http');
var fs = require('fs');
var path = require('path');

http.createServer(function (request, response) {

    var filePath = '.' + request.url;
    if (filePath == './')
       filePath = './index.html';

    var extName = path.extname(filePath);
    var contentType = 'text/html';
    switch (extName) {
        case '.js':
            contentType = 'text/javascript';
            break;
        case '.css':
            contentType = 'text/css';
            break;
    }

    path.exists(filePath, function(exists) {

    if (exists) {
        fs.readFile(filePath, function(error, content) {
            if (error) {
                response.writeHead(500);
                response.end();
            }
            else {
                response.writeHead(200, { 'Content-Type': contentType });
                response.end(content, 'utf-8');
            }
        });
    }
    else {
        response.writeHead(404);
        response.end();
    }
  });
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM