对 Node 的文件系统解析感到困惑。这是我的代码:
var fs = require('fs'),
xml2js = require('xml2js');
var parser = new xml2js.Parser();
var stream = fs.createReadStream('xml/bigXML.xml');
stream.setEncoding('utf8');
stream.on('data', function(chunk){
parser.parseString(chunk, function (err, result) {
console.dir(result);
console.log('Done');
});
});
stream.on('end', function(chunk){
// file have been read over,do something...
console.log("IT'S OVER")
});
这会导致……什么都不会发生。根本没有来自 XML2JS/解析器的输出。当我尝试 console.log(chunk)似乎chunks不会基于除字节大小之外的任何其他任何有意义的 block 输出。一个“ block ”的输出是:
<?xml version="1.0" encoding="UTF-8"?>
<merchandiser xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="merchandiser.xsd">
<header><merchantId>1237</merchantId><merchantName>NORDSTROM.com</merchantName><createdOn>12/13/2013 23:50:57</createdOn></header>
<product product_id="52863929">// product info</product>
<product product_id="26537849">// product info</product>
<product product_id="25535647">// product info</product>
这个 block 有很多很多 <product>来自其中的 XML 的条目。该 block 将在 <product> 的中间某处结束。条目和下一个 block 将从它停止的地方开始。
主要问题是我如何获得createReadStream输出从 <product 开始的 block 结束于 </product> ?
编辑:为了获得正确的输出,这里是第一个 <product> 的从头到尾的 XML。看起来像:
<?xml version="1.0" encoding="UTF-8" ?>
<merchandiser xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="merchandiser.xsd">
<header>
<merchantId>1237</merchantId>
<merchantName>NORDSTROM.com</merchantName>
<createdOn>12/13/2013 23:50:57</createdOn>
</header>
<product product_id="52863929" name="Teva 'Psyclone' Print Sandal (Baby, Walker & Toddler) Camo/ Dark Olive 6 M" sku_number="52863929" manufacturer_name="Teva" part_number="1001701">
<category>
<primary>Toddler Unisex</primary>
<secondary>Shoes~~Sandals/Slides</secondary>
</category>
<URL>
<product>http://click.linksynergy.com/link?id=LUyP0GcLCGc&offerid=276223.52863929&type=15&murl=http%3A%2F%2Fshop.nordstrom.com%2FS%2F3297406%3Fcm_cat%3Ddatafeed%26cm_pla%3Dshoes%3Asandals%252fslides%26cm_ite%3Dteva_%2527psyclone%2527_print_sandal_%2528baby%252c_walker_%2526_toddler%2529%3A503158_1%26cm_ven%3DLinkshare</product>
<productImage>http://content.nordstrom.com/imagegallery/store/product/large/0/_6880020.jpg</productImage>
<buy></buy>
</URL>
<description>
<short>Rugged construction and stylish good looks define a sporty sandal, with the added convenience and security of hook-and-loop closures across the toe and at the instep.Rugged construction and stylish good looks define a sporty sandal, with the added
convenience and security of h...</short>
<long>Rugged construction and stylish good looks define a sporty sandal, with the added convenience and security of hook-and-loop closures across the toe and at the instep.Rugged construction and stylish good looks define a sporty sandal, with the added
convenience and security of hook-and-loop closures across the toe and at the instep. Color(s): camo/ dark olive, daisy blue. Brand: Teva. Style Name: Teva 'Psyclone' Print Sandal (Baby, Walker & Toddler). Style Number: 503158_1.</long>
</description>
<discount currency="USD">
<amount></amount>
<type>amount</type>
</discount>
<price currency="USD">
<sale begin_date="" end_date="">24.95</sale>
<retail>24.95</retail>
</price>
<brand>Teva</brand>
<shipping>
<cost currency="USD">
<amount>0.00</amount>
<currency>USD</currency>
</cost>
<information></information>
<availability>Y</availability>
</shipping>
<keywords></keywords>
<upc>737872649135</upc>
<m1>503158_1.</m1>
<pixel>http://ad.linksynergy.com/fs-bin/show?id=LUyP0GcLCGc&bids=276223.52863929&type=15&subid=0</pixel>
<attributeClass class_id="60">
<Misc></Misc>
<Product_Type>Shoes</Product_Type>
<Size>6 M</Size>
<Material></Material>
<Color>CAMO/ DARK OLIVE</Color>
<Gender>Unisex</Gender>
<Style></Style>
<Age></Age>
</attributeClass>
</product>
最佳答案
您有两种可能性来解决您的问题。
正如 damphat 所述,XML2JS 在解析数据之前需要完整的 XML 内容。但是您有一个文件流,它逐 block 流式传输数据。第一个解决方案是将这个数据流转换成一个漂亮的大缓冲区,然后将它发送到 XML2JS。为此,您可以使用 stream-to package (npm i stream-to) 会将文件流转换为缓冲区数组,然后我们将使用 Buffer.concat 将其连接成一个缓冲区。 ,像这样:
var fs = require('fs')
var streamTo = require('stream-to')
var xml2js = require('xml2js')
var file = fs.createReadStream('input.xml')
streamTo.array(file, function (err, arr) {
if (err) return console.log(err.message)
var content = Buffer.concat(arr)
var parser = new xml2js.Parser()
parser.parseString(content, function (err, res) {
if (err) return console.log(err.message)
console.log(res.merchandiser.product)
})
})
这工作得很好,但由于它需要将整个文件保存到内存中,如果您的输入文件非常大,它就无法工作。要处理非常大的文件,您需要使用流式 XML 解析器,例如 sax。然而,sax 不创建 Javascript 对象,而是一个 EventEmitter,并且使用起来有点困难,因为您必须处理所有相关事件才能动态构建您的对象。
您可以使用例如 SaXPath library ,它支持一小部分 XPath 语法。每次匹配 XPath 模式时,该库都会发出一个 match 事件。这是一个例子:
var saxpath = require('saxpath')
var fs = require('fs')
var sax = require('sax')
var saxParser = sax.createStream(true)
var streamer = new saxpath.SaXPath(saxParser, '/merchandiser/product')
streamer.on('match', function(xml) {
console.log(xml);
});
fs.createReadStream('input.xml').pipe(saxParser)
然后你有两个选择:
xml2js 一次解析一种产品关于javascript - NodeJS parseStream,定义一个 block 的起点和终点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20603088/
我正在尝试设置一个puppet节点,但rubygems似乎不正常。如果我通过它自己的二进制文件(/usr/lib/ruby/gems/1.8/gems/facter-1.5.8/bin/facter)在cli上运行facter,它工作正常,但如果我通过由rubygems(/usr/bin/facter)安装的二进制文件,它抛出:/usr/lib/ruby/1.8/facter/uptime.rb:11:undefinedmethod`get_uptime'forFacter::Util::Uptime:Module(NoMethodError)from/usr/lib/ruby
使用带有Rails插件的vim,您可以创建一个迁移文件,然后一次性打开该文件吗?textmate也可以这样吗? 最佳答案 你可以使用rails.vim然后做类似的事情::Rgeneratemigratonadd_foo_to_bar插件将打开迁移生成的文件,这正是您想要的。我不能代表textmate。 关于ruby-使用VimRails,您可以创建一个新的迁移文件并一次性打开它吗?,我们在StackOverflow上找到一个类似的问题: https://sta
我需要从一个View访问多个模型。以前,我的links_controller仅用于提供以不同方式排序的链接资源。现在我想包括一个部分(我假设)显示按分数排序的顶级用户(@users=User.all.sort_by(&:score))我知道我可以将此代码插入每个链接操作并从View访问它,但这似乎不是“ruby方式”,我将需要在不久的将来访问更多模型。这可能会变得很脏,是否有针对这种情况的任何技术?注意事项:我认为我的应用程序正朝着单一格式和动态页面内容的方向发展,本质上是一个典型的网络应用程序。我知道before_filter但考虑到我希望应用程序进入的方向,这似乎很麻烦。最终从任何
我想要做的是有2个不同的Controller,client和test_client。客户端Controller已经构建,我想创建一个test_clientController,我可以使用它来玩弄客户端的UI并根据需要进行调整。我主要是想绕过我在客户端中内置的验证及其对加载数据的管理Controller的依赖。所以我希望test_clientController加载示例数据集,然后呈现客户端Controller的索引View,以便我可以调整客户端UI。就是这样。我在test_clients索引方法中试过这个:classTestClientdefindexrender:template=>
我在我的项目中添加了一个系统来重置用户密码并通过电子邮件将密码发送给他,以防他忘记密码。昨天它运行良好(当我实现它时)。当我今天尝试启动服务器时,出现以下错误。=>BootingWEBrick=>Rails3.2.1applicationstartingindevelopmentonhttp://0.0.0.0:3000=>Callwith-dtodetach=>Ctrl-CtoshutdownserverExiting/Users/vinayshenoy/.rvm/gems/ruby-1.9.3-p0/gems/actionmailer-3.2.1/lib/action_mailer
我有一些Ruby代码,如下所示:Something.createdo|x|x.foo=barend我想编写一个测试,它使用double代替block参数x,这样我就可以调用:x_double.should_receive(:foo).with("whatever").这可能吗? 最佳答案 specify'something'dox=doublex.should_receive(:foo=).with("whatever")Something.should_receive(:create).and_yield(x)#callthere
我想向我的Controller传递一个参数,它是一个简单的复选框,但我不知道如何在模型的form_for中引入它,这是我的观点:{:id=>'go_finance'}do|f|%>Transferirde:para:Entrada:"input",:placeholder=>"Quantofoiganho?"%>Saída:"output",:placeholder=>"Quantofoigasto?"%>Nota:我想做一个额外的复选框,但我该怎么做,模型中没有一个对象,而是一个要检查的对象,以便在Controller中创建一个ifelse,如果没有检查,请帮助我,非常感谢,谢谢
我已经从我的命令行中获得了一切,所以我可以运行rubymyfile并且它可以正常工作。但是当我尝试从sublime中运行它时,我得到了undefinedmethod`require_relative'formain:Object有人知道我的sublime设置中缺少什么吗?我正在使用OSX并安装了rvm。 最佳答案 或者,您可以只使用“require”,它应该可以正常工作。我认为“require_relative”仅适用于ruby1.9+ 关于ruby-主要:Objectwhenrun
如果您尝试在Ruby中的nil对象上调用方法,则会出现NoMethodError异常并显示消息:"undefinedmethod‘...’fornil:NilClass"然而,有一个tryRails中的方法,如果它被发送到一个nil对象,它只返回nil:require'rubygems'require'active_support/all'nil.try(:nonexisting_method)#noNoMethodErrorexceptionanymore那么try如何在内部工作以防止该异常? 最佳答案 像Ruby中的所有其他对象
关闭。这个问题需要detailsorclarity.它目前不接受答案。想改进这个问题吗?通过editingthispost添加细节并澄清问题.关闭8年前。Improvethisquestion为什么SecureRandom.uuid创建一个唯一的字符串?SecureRandom.uuid#=>"35cb4e30-54e1-49f9-b5ce-4134799eb2c0"SecureRandom.uuid方法创建的字符串从不重复?