如何使用Nodejs SDK从CosmosDB获取附件?

我正在尝试在Nodejs中使用CosmosDB。 我在一个集合中创build了一些文档,并添加了几个附件到一个文档中,如下所示:

let dbds = new azure(dbEndpoint, {"masterKey":dbKey}) fs.open("c:/temp/capture.png", "r", (err, fd) => { if(err) console.log(err); else{ dbds.createAttachmentAndUploadMedia(documentLink, fs, {contentType:"image/png", partitionKey: partitionKey}, (err, result) =>{ fs.close(fd); if(err) console.log(err); else console.log(result); } } } 

现在当我读到那个文件的附件时,我得到2个附件:

 dbds.readAttachments(documentLink, {"partitionKey":partitionKey}).toArray((err, result) => { if(err) console.log(err); else { console.log(result.length); //2 result.forEach(i => console.log(i.id);) //id of each attachment } } 

现在我需要能够读取文档并将其存储在本地。 似乎没有任何文档可以在Nodejs中find。 我已经尝试了以下内容:

 let attachment = result[0]; //from result of toArray() above -- first attachment from list let mediaURI = `${attachment._self}${attachment.media}` dbds.readMedia(mediaURI, (err, result) => { if(err) console.log(JSON.parse(err.body).message); //Request url is invalid else { //try to write result to file } } 

如何为媒体创build一个有效的URI来下载它?

编辑

根据下面的评论,我更新了我的代码如下:

 let attachment = result[0] let mediaURI = attachment.media //here is the change dbds.readMedia(mediaURI, (err, result) => { if(err) console.log(JSON.parse(err.body).message); else { //try to store the data } }) 

我不再得到一个错误,而是得到一个JSON对象:

 "{"constants":{"O_RDONLY":0,"O_WRONLY":1,"O_RDWR":2,"S_IFMT"‌​:61440,"S_IFREG":327‌​68,"S_IFDIR":16384,"‌​S_IFCHR":8192,"S_IFL‌​NK":40960,"O_CREAT":‌​256,"O_EXCL":1024,"O‌​_TRUNC":512,"O_APPEN‌​D":8,"F_OK":0,"R_OK"‌​:4,"W_OK":2,"X_OK":1‌​},"F_OK":0,"R_OK":4,‌​"W_OK":2,"X_OK":1}" 

在你的例子中,mediaURI应该是$ {attachment.media}而不是连接$ {attachment._self}。

这是一个片段:

 return new Promise<any>((resolve, reject) => { this.documentDbClient.readAttachment(docLink, options, (err, result) => { if (err) return reject(err); resolve(result.media); }); }).then((medialink) => { return new Promise<any>((resolve, reject) => { this.documentDbClient.readMedia(medialink, (err, result) => { if (err) return reject(err); // buffered data const data = []; result.on('data', (chunk) => data.push(chunk)); result.on('end', () => { resolve(data.join('')); }); // if not buffered // resolve(result.toString()); }); }); }); 

我在这方面得到了微软一些人的帮助。

主要的问题是我没有正确写入文件。

而不是这个

 let dbds = new azure(dbEndpoint, {"masterKey":dbKey}) fs.open("c:/temp/capture.png", "r", (err, fd) => { if(err) console.log(err); else{ dbds.createAttachmentAndUploadMedia(documentLink, fs, {contentType:"image/png", partitionKey: partitionKey}, (err, result) =>{ fs.close(fd); if(err) console.log(err); else console.log(result); } } } 

使用fs.open fs不是文件stream – 这是createAttachmentAndUploadMedia正在寻找的。 我错误地认为fs是fs.open创build的一个文件stream。

我最终做的是如下:

 fs.readFile("c:/temp/myimage.jpg",(err, data) => { if(err) reject(err); else dbds.svc.createAttachmentAndUploadMedia(docPath,data,{contentType: "image/jpeg" , partitionKey: "Key"}, (err, result) =>{..} })