如何修复 "XLSX.utils.json_to_sheet is not a function" 错误?

How to fix "XLSX.utils.json_to_sheet is not a function" error?

我做了一个 js 脚本来将 JSON 对象转换为 excel 文件。当我在命令行中使用模拟 JSON 对象执行该脚本时,该脚本有效,但是当我从 node-red 的节点 "file function" 调用它时,我收到错误:"TypeError: XLSX.utils.json_to_sheet is not a function"。 这是我的脚本:

const XLSX = require('xlsx');
const wb = { SheetNames: [], Sheets: {} };
const json = msg.questions;

console.log(json);

const ws = XLSX.utils.json_to_sheet(json);

const sheetName = "test sheet";
XLSX.utils.book_append_sheet(wb, ws, sheetName);

XLSX.writeFile(wb, 'output.xlsx');

因为require不在函数节点的范围内(这也适用于文件函数节点)。

有关如何包含额外模块的信息,请参阅文档:https://nodered.org/docs/writing-functions#loading-additional-modules

基本上您需要将模块添加到全局上下文并从那里包含它们。

(P.S.File功能节点已经4年多没更新了,核心功能节点已经走了很长一段路)