从 JSON 对象创建读取流对象

Creat ReadStream object from JSON object

我正在使用 jira-client npm 来处理 jira rest API ,我正在尝试使用 addAttachmentOnIssue 方法向工单添加附件,此方法需要问题的关键作为字符串参数并且还需要 ReadStream 作为第二个参数,如果我按照以下步骤操作,我可以将文件附加到票证:

var jiraAPI = require('jira-client');
var jira = new JiraApi({
protocol: "https",
host:"myJiraInstance",
username:"myUserName",
password: "MyToken",
apiVersion: "2",
strictSSL: true,})

然后

const fileStream = fs.createReadStream(filePath);
jira.addAttachmentOnIssue(tickeID,fileStream);

如您所见,我有文件路径并附加了它,但这不是我想要的,我想从 JSON 对象创建一个文件,而不是在系统上写入该文件然后发送它

这可能吗?

通过使用:

var stream = require('stream');
var readable = new stream.Readable(); // new empty stream.Readable
readable.push('some data');
readable.push(null);
jira.addAttachmentOnIssue(tciketID,readable)

我得到:

Processing of multipart/form-data request failed. Stream ended unexpectedly

问题是缺少所需的文件相关信息,如文件名、已知长度等,这就是解析流失败的原因。

您需要手动提供文件相关信息

因为 jira-client 使用 postman-request,您可以通过提供自定义文件对象来做到这一点,如下所述: multipart/form-data (Multipart Form Uploads)

试试这个:

var JiraApi = require('jira-client');
var jira = new JiraApi({
    protocol: "https",
    host: "myJiraInstance",
    username: "myUserName",
    password: "MyToken",
    apiVersion: "2",
    strictSSL: true
})



const inputData = JSON.stringify({
    someProp: 'some data'
});

var stream = require('stream');
var readable = new stream.Readable();
readable.push(inputData);
readable._read = () => {};
readable.push(null);


// https://www.npmjs.com/package/postman-request#forms
// Pass optional meta-data with an 'options' object with style: {value: DATA, options: OPTIONS}
// Use case: for some types of streams, you'll need to provide "file"-related information manually.
// See the `form-data` README for more information about options: https://github.com/form-data/form-data
const myStreamFile = {
    value: readable,
    options: {
        filename: 'json.json',
        contentType: 'application/json',
        knownLength: inputData.length
    }
}


jira.addAttachmentOnIssue(tciketID, myStreamFile)