如何使用 node.js 在 html 中调用外部 javascript 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19931233/
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
how to call external javascript file in html using node.js
提问by Pradeep Raj
I am a complete node.js newbie and struggling with the basics.I have a html file and I would like to call external javascript file in the html page using node.js in local host environment.
我是一个完整的 node.js 新手并且在基础知识方面苦苦挣扎。我有一个 html 文件,我想在本地主机环境中使用 node.js 在 html 页面中调用外部 javascript 文件。
JS:
JS:
var http = require('http'),
fs = require('fs');
fs.readFile('HtmlPage.html', function (err, html) {
if (err) {
throw err;
}
});
http.createServer(function(request, response) {
response.writeHeader(200, {"Content-Type": "text/html"});
response.write(html);
response.end();
}).listen(8000);});
HTML:
HTML:
<script type="text/javascript" >
function validation() {
alert("Hai");
var fs = require("JavaScript1.js");
}
</script>
回答by Hector Correa
Keep in mind that the JavaScript that you have in the HTML page will run on the browser, not on the server.
请记住,您在 HTML 页面中使用的 JavaScript 将在浏览器上运行,而不是在服务器上。
Therefore your alert("Hai");
will execute just fine since that's typical client-side javascript code, but server-side code like var fs = require("JavaScript1.js")
; will not.
因此,您alert("Hai");
将执行得很好,因为这是典型的客户端 javascript 代码,但服务器端代码如var fs = require("JavaScript1.js")
; 将不会。
There are ways to share client and server side javascript code as others pointed out in the comments, but I suspect that's not what you are after given that you are starting to learn Node.js
正如其他人在评论中指出的那样,有多种方法可以共享客户端和服务器端 javascript 代码,但我怀疑这不是您所追求的,因为您正在开始学习 Node.js
The fact that you are using Node.js in the server does not give you new JavaScript powers on the client side automatically. As far as the browser is concerned the server could be Ruby or C#.
您在服务器中使用 Node.js 的事实不会自动在客户端为您提供新的 JavaScript 功能。就浏览器而言,服务器可以是 Ruby 或 C#。
Also, I would write your server-side code like this:
另外,我会像这样编写您的服务器端代码:
var http = require('http'),
var fs = require('fs');
http.createServer(function(request, response) {
fs.readFile('HtmlPage.html', function (err, html) {
if (err) {
throw err;
}
response.writeHeader(200, {"Content-Type": "text/html"});
response.write(html);
response.end();
});
}).listen(8000);});
I've got an Intro to Node.js blog post that might help you in the beginning: http://hectorcorrea.com/blog/introduction-to-node-js
我有一篇介绍 Node.js 的博客文章,可能对您有所帮助:http: //hectorcorrea.com/blog/introduction-to-node-js