无法使用 Firebase Cloud Functions 创建 xlsx 文件

Utk*_*rsh 4 node.js firebase google-cloud-functions

我遵循了excel4node 包的基本使用教程

为了运行代码,我有一个 https 函数,它将在与本地系统Excel.xlsx相同的目录中创建一个文件。index.js

然而,问题是每次我调用该函数时,Excel.xls都会创建一个零字节文件。

函数体是这样的:

const createXlxsFile = (req, res) => {
  const xl = require('excel4node');

  // Create a new instance of a Workbook class
  const workbook = new xl.Workbook();

  // Add Worksheets to the workbook
  const worksheet = workbook.addWorksheet('Sheet 1');
  const worksheet2 = workbook.addWorksheet('Sheet 2');

  // Create a reusable style
  const style = workbook.createStyle({
    font: {
      color: '#FF0800',
      size: 12
    },
    numberFormat: '$#,##0.00; ($#,##0.00); -'
  });

  // Set value of cell A1 to 100 as a number type styled with paramaters of style
  worksheet.cell(1, 1).number(100).style(style);

  // Set value of cell B1 to 300 as a number type styled with paramaters of style
  worksheet.cell(1, 2).number(200).style(style);

  // Set value of cell C1 to a formula styled with paramaters of style
  worksheet.cell(1, 3).formula('A1 + B1').style(style);

  // Set value of cell A2 to 'string' styled with paramaters of style
  worksheet.cell(2, 1).string('string').style(style);

  // Set value of cell A3 to true as a boolean type styled with paramaters of style but with an adjustment to the font size.
  worksheet.cell(3, 1).bool(true).style(style).style({ font: { size: 14 } });

  workbook.write('Excel.xlsx');

  res.end('DOC CREATED');
};
Run Code Online (Sandbox Code Playgroud)

此代码可以在标准 Node.js 中正常运行,但不能在 Firebase 云函数中运行。函数写入文件有限制吗?

即使使用Xlsx-populate 包,我也遇到同样的问题。

Utk*_*rsh 6

好的。弄清楚了问题。

问题是云功能不允许您写入操作系统中的任何目录。

您拥有写入权限的唯一位置是/tmp云中的函数。

然而,在您的本地 PC 上,这也会崩溃(在 Windows 10 中测试)。可能是因为我没有创建C:/tmp文件夹。

要解决这个问题,可以使用Node.js 中模块tmpdir()的方法os

const os = require('os');
const path = require('path');
const pathToSave = path.join(os.tmpdir(), 'Excel.xlsx');
Run Code Online (Sandbox Code Playgroud)

部署代码时,您需要将其替换os.tmpdir()为“/tmp”。

const pathToSave = path.join('/tmp', 'Excel.xlsx');
Run Code Online (Sandbox Code Playgroud)

我希望这有帮助。