nodejs / express / oboe.js&pug:获取node()事件来更新dom

第一次使用节点和模板引擎(是的,我知道,可怕的地方“开始”,但不pipe)。 我从jsonstream构build一些内容,最后我想吐出这个内容到我的html页面的一个div,如下面这个( 更新 )expressjs片段:

app.get('/foo', function (req, res) { //... get my stream called 'mystream' //... get ready to append content for items found in json stream var htmlbuf = ""; //now process the json stream: oboe(mystream) .node('{bar}', function(aBar){ //eventually, I'd like to actually append individual new DOM elements, //but for now I'll settle for just spitting out raw html: var buffer = '<p>Found a bar with name'+ aBar.name + '</p>'; res.render('index', {itemsfound: htmlbuf}); }); }); 

index.pug:

 doctype html html head link(type='text/css', rel='stylesheet', href='./css/main.css') title Hello body h1 Hello world! div#results.listing items= itemsfound 

我收到错误“ 错误:发送后无法设置标题 ”。 所以我相信问题是oboe.node()随时都在发射,我没有在正确的时间发送响应内容? 连接oboe.node()事件所需的代码/框架是什么,以便他们可以在我的帕格模板中定位或创builddom元素,并正确地发送响应? 谢谢。

你需要做这样的事情:

 app.get('/foo', function (req, res, next) { //... get my stream called 'mystream' //... get ready to append content for items found in json stream var htmlbuf = ""; //now process the json stream: oboe(mystream) .node('{bar}', function(aBar){ //eventually, I'd like to actually append individual new DOM elements, //but for now I'll settle for just spitting out raw html: htmlbuf += '<p>Found a bar with name' + aBar.name + '</p>'; }) .on('fail', function (err) { res.statusCode = err.statusCode next(err.thrown) }) .on('done', function () { res.render('index', {itemsfound: htmlbuf}); }); }); 

好,我会试试。

如果你想渲染页面的计算内容然后

 // js app.get('/foo', function (req, res) { res.locals.var1 = 'Res.locals.var1'; // you can define vars here too if (!req.xhr) // send as html-page res.render('page.jade', {bar: smth-content, title: 'Hello world'}); // without var1 else // send as json on ajax-request res.json({bar: smth-content, title: 'Hello world'}); }); // .jade doctype html html head link(type='text/css', rel='stylesheet', href='./css/main.css') | title #{title} body h1 Hello world! | #{bar} #{var1} 

要混合模板代码,您可以使用extendsinclude玉关键字。 或者这个技巧(不推荐)

 // js app.get('/foo', function (req, res) { res.render('row.jade', {myblock: smth-content}, function(err, html) { if (err) return res.send(err.message); res.render('page.jade', {myblock: html}); }); }); // page.jade doctype html html head link(type='text/css', rel='stylesheet', href='./css/main.css') body #{myblock} // myblock.jade p Found a bar with name #{myblock}