如何将节点函数的结果写入html / console日志?

我是新的节点,我试图将结果打印到控制台,并最终显示在HTML中。 我已经尝试调用函数作为我以后在HTML中使用的var,但是这不起作用。 一些类似的示例代码:

var app = require('express')(); var x = require('x-ray')(); app.get('/', function(req, res) { res.send(x('http://google.com', 'title').write()); }) 

谢谢!

我对“X射线”库不太了解,但是我认为问题在于,因为在返回响应数据之前它必须asynchronous地发出请求。 该文件说,如果你没有设置一个path作为写入函数的参数,它返回一个可读的stream,所以试试这个:

 app.get('/', function(req, res) { var stream = x('http://google.com', 'title').write(), responseString = ''; stream.on('data', function(chunk) { responseString += chunk; }); stream.on('end', function() { res.send(responseString); }); }); 

您还需要启动侦听特定端口的服务器(在下面的示例中为3000):

 const PORT = 3000; app.listen(PORT, function() { console.log("Server is listening on port " + PORT + "."); }); // the callback function simply runs once the server starts 

现在打开你的浏览器并导航到127.0.0.1:3000localhost:3000 ,你会看到“Google”出现!


另外:如果您想在完整的HTML页面中使用响应数据(而不是仅仅发送string),您可能需要进一步探索如何使用Jade(或类似)模板在Express中执行此操作。 而且,每当有人向您的服务器的相应路由请求时,此刻的代码就会向Google进行刮擦。 如果你只想刮一次Google,然后在服务器的响应中一次又一次地使用相同的string,你可能想要考虑如何实现这个(很简单!)。