我有一个节点后端,我正在进行文件上传。以下对我有用:
var options = {
method: 'POST',
uri: 'xxx',
formData: {
file: {
value: fs.createReadStream('new1.css'),
options: {
contentType: 'text/css'
}
}
}
};
let resp: any = await request(options);
但是,在我的情况下,我将不会有一个我可以阅读的文件。我将只是一个CSS字符串。如何将我的css字符串转换为类似于fs.createReadStream('new1.css')的格式
我尝试从下面的答案接近,但它对我不起作用。我试过打印JSON.stringify(fs.createReadStream('new1.css'))并输出:
{"_readableState":{"objectMode":false,"highWaterMark":65536,
"buffer":{"head":null,"tail":null,"length":0},
"length":0,
"pipes":null,
"pipesCount":0,
"flowing":null,
"ended":false,
"endEmitted":false,
"reading":false,
"sync":true,
"needReadable":false,
"emittedReadable":false,
"readableListening":false,
"resumeScheduled":false,
"defaultEncoding":"utf8",
"ranOut":false,
"awaitDrain":0,
"readingMore":false,
"decoder":null,
"encoding":null},
"readable":true,
"domain":null,
"_events":{},
"_eventsCount":1,
"path":"new2.css",
"fd":null,
"flags":"r",
"mode":438,
"autoClose":true,
"bytesRead":0}
我还打印了JSON.stringify(css),输出为:
{"_readableState":{"objectMode":false,"highWaterMark":16384,
"buffer":{"head":{"data":{"type":"Buffer","data":[98,111,100,121,32,123,125]},"next":null},
"tail":{"data":{"type":"Buffer","data":[98,111,100,121,32,123,125]},"next":null},"length":1},
"length":7,
"pipes":null,
"pipesCount":0,
"flowing":null,
"ended":true,
"endEmitted":false,
"reading":false,
"sync":true,
"needReadable":false,
"emittedReadable":true,
"readableListening":false,
"resumeScheduled":false,
"defaultEncoding":"utf8",
"ranOut":false,
"awaitDrain":0,
"readingMore":true,
"decoder":null,
"encoding":null},
"readable":true,
"domain":null,
"_events":{},
"_eventsCount":0}
我不确定导致此问题的区别。以及如何解决它
答案 0 :(得分:0)
使用Node.js Stream API,创建Readable
流并推送您的CSS
var Readable = require('stream').Readable
var css = new Readable
css.push('body {}') // your css string
css.push(null) // indicates the end of the stream
var options = {
method: 'POST',
uri: 'xxx',
formData: {
file: {
value: css,
options: {
contentType: 'text/css'
}
}
}
};
let resp: any = await request(options)