简体   繁体   English

使用Node.js提供JavaScript文件

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

I'm trying to serve up some static files using an extremely basic node.js server. 我正在尝试使用一个非常基础的node.js服务器提供一些静态文件。 The aim is to serve a html file with a script tag referencing a javascript file. 目的是为HTML文件提供带有引用JavaScript文件的脚本标签。 When opening the application in the browser the html renders fine, the problem is with the js file. 在浏览器中打开应用程序时,html呈现良好,问题出在js文件上。 In the browser the js file has the html code in it and not the js code. 在浏览器中,js文件中包含html代码,而不包含js代码。

SERVERC CODE: 服务器代码:

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): 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): JAVASCRIPT CODE(some.js):

console.log("Hello")

DIRECTORY STRUCTURE: 目录结构:

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

I would advise you to create a directory for the files that you need to serve in the following manner 我建议您以以下方式为需要服务的文件创建目录

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

Then you use express.static to serve that directory you created. 然后,您使用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)
})

Then you just run 那你就跑

node app.js

Without using express you can do the following 不使用快递,您可以执行以下操作

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