0

我有一个节点后端,我正在执行文件上传。以下对我有用:

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}

我不确定是哪个差异导致了这个问题。以及如何解决它

4

1 回答 1

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)
于 2017-10-13T22:45:55.763 回答