'路徑必須是一個沒有空字節的字符串'我有一個從base64經過加載的圖像創建的緩衝區。我試着用POST發送到與fs.createReadStream服務(..)管(請求(..)),但出現以下錯誤:當管道流請求
Error: Path must be a string without null bytes
at nullCheck (fs.js:135:14)
at Object.fs.open (fs.js:626:8)
at ReadStream.open (fs.js:1916:6)
at new ReadStream (fs.js:1903:10)
at Object.fs.createReadStream (fs.js:1850:10)
at Promise (/Users/Sebbe/Documents/Code/leo-faq-service/lib/server/services/zendesk-service.js:120:10)
[...]
fs.createReadStream()它可以是一個字符串或緩衝。如果它是一個字符串,那麼它應該是一個文件的路徑。在我看來,fs.createReadStream()嘗試將參數解析爲包含路徑的字符串,即使它是一個緩衝區。這可能是Nodes Buffer API中的一個錯誤嗎?
更多細節:
我有一個內置的RESTify節點的服務。該服務有一個端點,需要一個主題,消息,名稱和base64編碼的圖像文件(jpg,png等)。
現在我們要在Node中使用JavaScript將文件的內容發送給第三方服務。
當我讀到這個時候,有幾個消息來源說我應該用一個Buffer-object創建一個「Readable Stream」,並將它傳遞給發送給第三方服務的請求。
因此,我從我的base64編碼圖像創建了一個Buffer,並將其作爲參數發送給fs.createReadStream,然後將其傳遞給請求對象。
根據這一點,我應該能夠創建一個base64字符串的緩衝區:https://nodejs.org/api/buffer.html#buffer_class_method_buffer_from_string_encoding
根據這一點,我應該能夠創建一個緩衝區可讀流:https://nodejs.org/api/fs.html#fs_fs_createreadstream_path_options
而根據本我應該能夠使用請求模塊,其管緩衝器到POST請求:https://www.npmjs.com/package/request從請求模塊文檔
引用:
You can also stream a file to a PUT or POST request. This method will also check the file extension against a mapping of file extensions to content-types (in this case application/json) and use the proper content-type in the PUT request (if the headers don’t already provide one).
fs.createReadStream('file.json').pipe(request.put(url))
_postFile(base64FileContent) {
const fileBuffer = Buffer.from(base64FileContent, 'base64');
const fileUploadOptions = this._getRequestPostFileOptions('uploads', fileBuffer.length);
return new Promise((resolve, reject) => {
fs.createReadStream(fileBuffer)
.pipe(request.post(fileUploadOptions)
.on('response', (response) => {
resolve(response);
})
.on('error', (error) => {
reject(error);
})
);
});
}
_getRequestPostFileOptions(resourceName, dataLength) {
return {
uri : url.parse(`${this.coreBaseUrl}/${resourceName}`),
timeout : RequestTimeout,
method : 'POST',
headers : {
'Authorization' : `Basic ${this.auth}`,
'Content-Type' : 'application/binary',
'Content-Length' : dataLength
}
};
}
這是什麼回報'url.parse(「$ {this.coreBaseUrl}/$ {}資源名稱')'? –
example: this.coreBaseUrl ='http://www.url.to/api' resourceName ='articles'or'user'or'comments' 然後我使用url.parse(..)來合併兩者都轉換爲有效的網址。 – Spetastium
你可以確認在執行'url.parse(..)'後它是否會作爲字符串傳遞? –