Node.js:创建一个 txt 文件而不写入设备

问题描述

我有问题。在我的项目中,我收到一个文本并将此文本发送到 .txt 文件中的远程 API。现在程序执行以下操作:获取文本,将文本保存在文件系统中的 .txt 文件中,将 .txt 文件上传到远程 API。不幸的是,远程 API 只接受文件,我无法在请求中发送纯文本。

//get the wallPost with the field text
fs.writeFileSync(`./tmp/${wallPostId}.txt`,wallPost.text)

remoteapi.uploadFileFromStorage(
  `${wallPostPath}/${wallPostId}.txt`,`./tmp/${wallPostId}.txt`
)

UPD:在函数uploadFileFromStorage 中,我通过写入文件向远程api 发出PUT 请求。远程API是云存储API,只能保存文件

const uploadFileFromStorage = (path,filePath) =>{
let pathEncoded = encodeURIComponent(path)
const requestUrl = `https://cloud-api.yandex.net/v1/disk/resources/upload?&path=%2F${pathEncoded}`
const options = {
  headers: headers
}

axios.get(requestUrl,options)

.then((response) => {
  const uploadUrl = response.data.href
  const headersupload = {
    'Content-Type': 'text/plain','Accept': 'application/json','Authorization': `${auth_type} ${access_token}`
  }
  const uploadOptions = {
    headers: headersupload
  }
  axios.put(
    uploadUrl,fs.createReadStream(filePath),uploadOptions
  ).then(response =>
    console.log('uploadingFile: data  '+response.status+" "+response.statusText)
  ).catch((error) =>
    console.log('error uploadFileFromStorage '+ +error.status+" "+error.statusText)
  )
})

但我想将来这样的过程会很慢。我想在 RAM 内存中创建和上传 .txt 文件(不写在驱动器上)。感谢您抽出宝贵时间。

解决方法

您正在使用 Yandex Disk API,它需要文件,因为这就是它的用途:它明确地将文件存储在远程磁盘上。

因此,如果您查看该代码,则提供文件内容的部分是通过 fs.createReadStream(filePath) 提供的,它是一个 Stream。该函数不关心构建该流的内容,它只关心它一个流,所以build your own from your in-memory data

const { Readable } = require("stream");

...

const streamContent = [wallPost.text];
const pretendFileStream = Readable.from(streamContent);

...

axios.put(
  uploadUrl,pretendFileStream,uploadOptions
).then(response =>
  console.log('uploadingFile: data  '+response.status+" "+response.statusText)
)

虽然我在您的代码中没有看到任何内容告诉 Yandex Disk API 文件名应该是什么,但我确定这只是因为您为简洁起见编辑了帖子。