【问题标题】:Node.js: create a txt file without writing to the deviceNode.js:创建一个txt文件而不写入设备
【发布时间】:2021-01-30 19:30:37
【问题描述】:

我有问题。在我的项目中,我得到一个文本并将此文本发送到 .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 请求。 Remote 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 文件(不写入驱动器)。感谢您的宝贵时间。

【问题讨论】:

  • 好的,哪个远程API?因为最明显的解决方案是“停止使用uploadFileFromStorage,它显然是用于文件,使用 API 调用来获取纯数据”,但是您没有为了解您正在使用的服务的人提供足够的信息来帮助您。
  • 哦,对不起,我忘了。 Remote API只接受文件,是云存储的api
  • 在 API 中,我无法弄清楚“接受纯文本”与“接受纯文本文件”之间的区别。
  • @Evert ,我添加了有关 api 的信息
  • 就接受数据的 API 端点而言,几乎可以肯定没有任何区别,但对于您在自己的代码中使用的 API ,区别在于“他们的代码”是做什么的。所以在这种情况下,介于“有一个缓冲区”与“需要在磁盘上存在一个文件”之间。

标签: javascript node.js fs yandex-api


【解决方案1】:

您正在使用 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 文件名应该是什么的内容,但我确信这只是因为您为了简洁而编辑了帖子。

【讨论】:

  • 非常感谢!当我得到测试结果时,我会写。并且文件名是在第一次请求的PATH参数中隐式传递的,与tmp文件夹中的临时文件名相同)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-29
  • 2014-01-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多