使用node.js nano模块将附件批量上传到couchDB

我正尝试使用node.js和nano将附件批量上传到CouchDB。 首先,walk模块用于查找上传文件夹中的所有文件,并从中创build数组。 接下来,数组中的每个文件都应该通过pipe道和nano模块插入到CouchDB中。 但是,最终的结果是只有一个附件已经上传。

var nano = require('nano')('http://localhost:5984') var alice = nano.use('alice'); var fs = require('fs'); var walk = require('walk'); var files = []; // Walker options var walker = walk.walk('./uploads', { followLinks: false }); // find all files and add to array walker.on('file', function (root, stat, next) { files.push(root + '/' + stat.name); next(); }); walker.on('end', function () { // files array ["./uploads/2.jpg","./uploads/3.jpg","./uploads/1.jpg"] files.forEach(function (file) { //extract file name fname = file.split("/")[2] alice.get('rabbit', {revs_info: true}, function (err, body) { fs.createReadStream(file).pipe( alice.attachment.insert('rabbit', fname, null, 'image/jpeg', { rev: body._rev }, function (err, body) { if (!err) console.log(body); }) ) }); }); }); 

这是因为你正在混合一个asynchronousAPI,并假设这是同步的。

第一次请求后你会得到冲突,导致兔子文件已经改变。

NANO_ENV=testing node yourapp.js来确认吗?

如果这是问题,我推荐使用asynchronous

 var nano = require('nano')('http://localhost:5984') var alice = nano.use('alice'); var fs = require('fs'); var walk = require('walk'); var files = []; // Walker options var walker = walk.walk('./uploads', { followLinks: false }); walker.on('file', function (root, stat, next) { files.push(root + '/' + stat.name); next(); }); walker.on('end', function () { series(files.shift()); }); function async(arg, callback) { setTimeout(function () {callback(arg); }, 100); } function final() {console.log('Done');} function series(item) { if (item) { async(item, function (result) { fname = item.split("/")[2] alice.get('rabbit', { revs_info: true }, function (err, body) { if (!err) { fs.createReadStream(item).pipe( alice.attachment.insert('rabbit', fname, null, 'image/jpeg', { rev: body._rev }, function (err, body) { if (!err) console.log(body); }) ) } }); return series(files.shift()); }); } else { return final(); } }