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

Node.js: create a txt file without writing to the device

我有问题。在我的项目中,我得到一个文本并将该文本发送到 .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 磁盘 API,它需要文件,因为这就是它的用途:它明确地将文件存储在远程磁盘上。

因此,如果您查看该代码,提供文件内容的部分是通过 fs.createReadStream(filePath) 提供的,这是一个流。该函数不关心构建那个流,它只关心它一个流,所以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 文件名应该是什么,但我敢肯定那只是因为您编辑了 post简洁。