-1

嗨,我曾尝试从我的 C 盘解压缩文件并尝试解析为 javascript 对象,这是代码

var AdmZip = require('adm-zip');
var fs = require('fs'), xml2js = require('xml2js');
var parser = new xml2js.Parser();
var paramdata = 'c:/sample/kusuma.zip';
console.log(paramdata);
var zip = new AdmZip(paramdata);
var zipEntries = zip.getEntries();
var obj = [];
var count = 0;
zipEntries.forEach(function(zipEntry) {
    var len = zipEntries.length;
    console.log(zipEntry.toString());
    console.log(zipEntry.entryName);
    fs.readFile("", function(err, data) {
        console.log(data);
        parser.parseString(data, function(err, result) {
            count++;
            console.log(count);
            obj.push(result);

            if (count === len) {
                console.log(obj);
                res.send(obj);
            }

        });
    });

});

请检查一次代码并提供更多示例

4

1 回答 1

0

Well, fs.readFile() is for reading files that are themselves directly on disk, which these aren't.

However, adm-zip is already reading in the contents of the .zip, so you shouldn't need fs. Each zipEntry has getData() and getDataAsync() methods that can be used to retrieve contents.

zipEntries.forEach(function (zipEntry) {
    zipEntry.getDataAsync(function (data) {
        parser.parseString(data, function (err, result) {
            console.log(result);
        });
    });
});

Also, as zipEntries is an Array, you can use .filter() to reduce it to only XML files.

var zipEntries = zip.getEntries().filter(function (zipEntry) {
    return !zipEntry.isDirectory && /\.xml$/.test(zipEntry.entryName);
});

You'll also want to determine len once from the collection rather than from each entry. You can also test that against use obj.length rather than having to keep count separately:

var len = zipEntries.length;
var obj = [];

zipEntries.forEach(function (zipEntry) {
    zipEntry.getDataAsync(function (data) {
        parser.parseString(data, function (err, result) {
            obj.push(result);

            if (obj.length === len) {
                res.send(obj);
            }
        });
    });
});
于 2013-08-17T06:43:06.677 回答