Node.js - 外部 JS 和 CSS 文件(只使用 node.js 不表达)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12134554/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Node.js - external JS and CSS files (just using node.js not express)
提问by Denim Demon
Im trying to learn node.js and have hit a bit of a roadblock.
我正在尝试学习 node.js 并且遇到了一些障碍。
My issue is that i couldn't seem to load an external css and js file into a html file.
我的问题是我似乎无法将外部 css 和 js 文件加载到 html 文件中。
GET http://localhost:8080/css/style.css 404 (Not Found)
GET http://localhost:8080/js/script.css 404 (Not Found)
(this was when all files were in the root of the app)
(这是所有文件都在应用程序的根目录中的时候)
I was told to somewhat mimic the following app structure, add a route for the public dir to allow the webserver to serve the external files.
有人告诉我有点模仿以下应用程序结构,为公共目录添加一个路由,以允许网络服务器为外部文件提供服务。
my app structure is like so
我的应用程序结构是这样的
domain.com
app/
webserver.js
public/
chatclient.html
js/
script.js
css/
style.css
So my webserver.js script is in the root of app, and everything I want to access is in 'public'.
所以我的 webserver.js 脚本位于 app 的根目录中,我想访问的所有内容都位于“公共”中。
I also saw this examplethat uses path.extname() to get any files extentions located in a path. (see the last code block).
我还看到了这个例子,它使用 path.extname() 来获取位于路径中的任何文件扩展名。(见最后一个代码块)。
So I've tried to combine the new site structure and this path.extname() example, to have the webserver allow access to any file in my public dir, so I can render the html file, which references the external js and css files.
所以我尝试将新的站点结构和这个 path.extname() 示例结合起来,让网络服务器允许访问我公共目录中的任何文件,这样我就可以呈现引用外部 js 和 css 文件的 html 文件.
My webserver.js looks like this.
我的 webserver.js 看起来像这样。
var http = require('http')
, url = require('url')
, fs = require('fs')
, path = require('path')
, server;
server = http.createServer(function(req,res){
var myPath = url.parse(req.url).pathname;
switch(myPath){
case '/public':
// get the extensions of the files inside this dir (.html, .js, .css)
var extname = mypath.extname(path);
switch (extname) {
// get the html
case '.html':
fs.readFile(__dirname + '/public/chatclient.html', function (err, data) {
if (err) return send404(res);
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data, 'utf8');
res.end();
});
break;
// get the script that /public/chatclient.html references
case '.js':
fs.readFile(__dirname + '/public/js/script.js', function (err, data) {
if (err) return send404(res);
res.writeHead(200, { 'Content-Type': 'text/javascript' });
res.end(content, 'utf-8');
res.end();
});
break;
// get the styles that /public/chatclient.html references
case '.css':
fs.readFile(__dirname + '/public/css/style.css', function (err, data) {
if (err) return send404(res);
res.writeHead(200, { 'Content-Type': 'text/javascript' });
res.end(content, 'utf-8');
res.end();
});
}
break;
default: send404(res);
}
});
Inside the case of public, I'm trying to get any of the folders/files inside of this dir via var extname = mypath.extname(path); Similar to the link I provided.
在 public 的情况下,我试图通过 var extname = mypath.extname(path); 获取此目录中的任何文件夹/文件;类似于我提供的链接。
But at the moment 'extname' is empty when I console log it.
但是目前当我控制台记录它时'extname'是空的。
Can anyone advise what I might need to add or tweek here? I'm aware this can be done easily in Express, but I would like to know how to achieve the same thing just relying on Node.
任何人都可以建议我可能需要在这里添加或 tweek 吗?我知道这可以在 Express 中轻松完成,但我想知道如何仅依靠 Node.js 来实现相同的目标。
I's appreciate any help on this.
我很感激这方面的任何帮助。
Thanks in advance.
提前致谢。
回答by saeed
There are several problems with your code.
您的代码有几个问题。
- Your server is not going to run as you have not specified a port to listen from.
- As Eric pointed out your case condition will fail as 'public' does not appear in the url.
- Your are referencing a non-existent variable 'content' in your js and css responses, should be 'data'.
- You css content-type header should be text/css instead of text/javascript
- Specifying 'utf8' in the body is unnecessary.
- 您的服务器不会运行,因为您没有指定要监听的端口。
- 正如 Eric 指出的,您的案例条件将失败,因为 'public' 没有出现在 url 中。
- 您在 js 和 css 响应中引用了一个不存在的变量“内容”,应该是“数据”。
- 你的 css 内容类型标题应该是 text/css 而不是 text/javascript
- 在正文中指定 'utf8' 是不必要的。
I have re-written your code. Notice I do not use case/switch. I prefer much simpler if and else, you can put them back if that's your preference. The url and path modules are not necessary in my re-write, so I have removed them.
我已经重写了你的代码。注意我不使用 case/switch。我更喜欢更简单的 if 和 else,如果这是你的偏好,你可以把它们放回去。url 和 path 模块在我的重写中不是必需的,所以我删除了它们。
var http = require('http'),
fs = require('fs');
http.createServer(function (req, res) {
if(req.url.indexOf('.html') != -1){ //req.url has the pathname, check if it conatins '.html'
fs.readFile(__dirname + '/public/chatclient.html', function (err, data) {
if (err) console.log(err);
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
res.end();
});
}
if(req.url.indexOf('.js') != -1){ //req.url has the pathname, check if it conatins '.js'
fs.readFile(__dirname + '/public/js/script.js', function (err, data) {
if (err) console.log(err);
res.writeHead(200, {'Content-Type': 'text/javascript'});
res.write(data);
res.end();
});
}
if(req.url.indexOf('.css') != -1){ //req.url has the pathname, check if it conatins '.css'
fs.readFile(__dirname + '/public/css/style.css', function (err, data) {
if (err) console.log(err);
res.writeHead(200, {'Content-Type': 'text/css'});
res.write(data);
res.end();
});
}
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');
回答by Kostia
You might want to look into using server frameworks like expresswhich allow you to set a 'public' directory for automatically routing static files
您可能想考虑使用express等服务器框架,它允许您设置“公共”目录以自动路由静态文件
var express = require('express'),app = express();
app.use(express.static(path.join(__dirname, 'public')));
The cheap overhead of such a framework would really be worth the effort of effectively 'reinventing the wheel'
这样一个框架的廉价开销真的值得有效地“重新发明轮子”
回答by Eric
publicdoes not appear in the URL requested by the client, so the switch on myPath will always fall through.
public没有出现在客户端请求的 URL 中,所以 myPath 上的 switch 总是会失败。
回答by Benjen
You could consider looking at the Staticmiddleware provided in Connect. Looking at Static's source code might give you some ideas on how to do this with node.js code (if you want learn how to do it without using an existing library).
您可以考虑查看Connect 中提供的静态中间件。查看 Static 的源代码可能会给您一些关于如何使用 node.js 代码执行此操作的想法(如果您想了解如何在不使用现有库的情况下执行此操作)。
回答by Allan Felipe Murara
Auto Update files on change, delay for update 1 sec. Format : app.js | index.htm | style.css
更改时自动更新文件,更新延迟 1 秒。格式:app.js | index.htm | 样式文件
// packages
const http = require('http');
const fs = require('fs');
// server properties
const hostname = '127.0.0.1';
const port = 3000;
const timer = 300;
//should trigger atualize function every timer parameter
let htmlfile = '';
let cssfile = '';
let jsfile = '';
uptodate();
// should read file from the disk for html
function uptodate()
{
console.log(1);
fs.readFile('./index.html', function (err, html) {
if (err) {
throw err;
}
htmlfile = html;
});
// should read css from the disk for css
fs.readFile('./style.css', function (err, html) {
if (err) {
throw err;
}
cssfile = html;
});
// should read js file from the disk
fs.readFile('./app.js', function (err, html) {
if (err) {
throw err;
}
jsfile = html;
});
setTimeout(function(){ uptodate(); }, 1000);
}
const server = http.createServer((req, res) => {
res.statusCode = 200;
// should send css and js
if(req.url.indexOf('.css') != -1){ //req.url has the pathname, check if it conatins '.js'
res.writeHead(200, {'Content-Type': 'text/css'});
res.write(cssfile);
res.end();
return;
}
if(req.url.indexOf('.js') != -1){ //req.url has the pathname, check if it conatins '.js'
res.writeHead(200, {'Content-Type': 'text/javascript'});
res.write(jsfile);
res.end();
return;
}
// should send html file via request
res.writeHeader(200, {"Content-Type": "text/html"});
res.write(htmlfile);
res.end();
});
// should send css and js
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
回答by Michael Blake
// get the extensions of the files inside this dir (.html, .js, .css)
var extname = **mypath**.extname(path);
These are reversed. Should be:
这些是反过来的。应该:
var extension = path.extname(mypath);
I also do not use function names for variable names when I can avoid it.
在可以避免的情况下,我也不使用函数名作为变量名。

