node js - 如何保存从电报机器人收到的文件

node js - How to save received file from telegram bot

如何从流或 nodejs 中的 url 保存文件? 我有一个电报机器人,可以从用户那里获取文件。我能够获取文件 url 或流,但我不确定如何在处理之前将其保存在临时目录中。

这是我正在使用的库link

我该如何继续?这是代码


#!/usr/bin/env node

const process = require('process');
const fs = require('fs');
const path = require('path');
const TelegramBot = require('node-telegram-bot-api');


const token = process.env.TELEGRAM_BOT_TOKEN || '5xxxxxxxxxxxxx';
// Create a bot that uses 'polling' to fetch new updates
const bot = new TelegramBot(token, {polling: true});  

bot.onText(/\/echo(.+)/, async (msg, match) => {
  // 'msg' is the received Message from Telegram
  // 'match' is the result of executing the regexp above on the text content
  // of the message
  //const chatId = msg.chat.id;
});

bot.on('message', async (msg) => {
...
});


bot.on('document', async (data) => {
  console.log(data);

  // here I'm getting the file url  
  const fileURL = await bot.getFileLink(data.document.file_id);
  // the library have a method that give the ability to get the file stream. How I save it to a file?
  const stream = await bot.getFileStream(data.document.file_id);
  console.log(fileURL, stream);
});

//

你可以这样做:

const { createWriteStream } = require('fs');

stream.pipe(createWriteStream('your_file'));