将本地js函数导入到node.js

我坚持了一会儿,认为这是因为我误解了node.js文件的链接。

我有以下结构:

./main_test.html ./js_test.js ./node_test.js 

main_test.html是:

 <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> </head> <body> <p id="p1"> </p> </body> </html> 

js_test包含一个将文本打印到id为p1<p>标记的函数,如下所示:

 module.exports.print_to_p = function(){ $("#p1").text('This worked.'); }; 

我的节点脚本应该为main_test.html提供服务,并从js_test.js运行该函数:

 var http = require('http'), fs = require('fs'), $ = require('jQuery'), port = 1337, dep1 = require('./js_test.js'); dep1.print_to_p(); var app = http.createServer(function(request, response) { fs.readFile("main_test.html", function(error, data) { if (error) console.log(error); response.writeHead(200, { 'Content-Type': 'text/html' }); response.write(data); response.end(); }); }).listen(port); 

它说ReferenceError: $ is not defined ,我认为是由于它没有引用JQuery,但将其改为document.getElementById('p1').innerHTML = 'This worked'; 没有解决这个问题。

我如何在我的节点应用程序中运行Javascript / JQuery?

问题是你的http请求不能处理你的链接文件,因为它们都被解释为html文件。 如果让您的服务器使用相同的内容types处理不同的文件types,则不能正确传递依赖关系。 您可以使用某些库或包(如express或mime-type) (这有助于单独识别内容types)来修复此问题,也可以通过识别相关文件的内容types并调整请求来手动执行此操作。

这样做的一个例子是修改你的node_test.js ,如下所示:

 var http = require('http'), fs = require('fs'), port = 1337, path = require('path'); var app = http.createServer(function (request, response) { var filePath = request.url; var extension = path.extname(filePath); var contentType = 'text/html'; // your default content-type switch (extension) { case '.js': contentType = 'text/javascript'; break; ... // here you can specify the content-types you need } fs.readFile(filePath, function(error, data) { if (error) console.log(error); response.writeHead(200, { 'Content-Type': contentType }); response.write(data); response.end(); }); }).listen(port); 

请注意,您还必须指定要在此处读取的文件! http请求被独立调用,这意味着每个文件都必须被处理和读取。 为了得到正确的文件扩展名,你可以使用一个名为path的节点包。

节点是服务器语言,不能访问DOM。 您可以创build节点服务器,它将托pipeHTML和JS文件,但是您将无法在节点中运行客户端JS代码。

你的代码应该是:

 <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <script src="js_test.js"></script> <script> print_to_p(); </script> </head> <body> <p id="p1"> </p> </body> </html> 

js_test.js

 function print_to_p(){ $("#p1").text('This worked.'); }; 

node_test.js

 var http = require('http'), fs = require('fs'), port = 1337, var app = http.createServer(function(request, response) { fs.readFile("main_test.html", function(error, data) { if (error) console.log(error); response.writeHead(200, { 'Content-Type': 'text/html' }); response.write(data); response.end(); }); }).listen(port); 

考虑一下node_test.js这行是否需要它来工作。

 dep1.print_to_p(); 

该函数的代码是引用jQuery $variables,但由于js_test.js没有定义一个会导致错误。

另一件事,即使$将被定义它将停止不知道的HTML页面本身。 这是在服务器上运行的Node.js。 如果您使用“服务器友好的jQuery”实现,例如cheerio,它会更好。 或者,如果您将这段JavaScript代码移动到您的HTML页面上。

你很近,继续努力。 缺less的链接是要实现服务器上正在运行的内容以及浏览器上正在运行的内容。