Search code examples
javascriptnode-redsheetjs

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


I did a js script to transform a JSON object to an excel file. The script works when I execute it in command line with a mock JSON object, but when I call it from the node "file function" of node-red, I get the error: "TypeError: XLSX.utils.json_to_sheet is not a function". Here is my script :

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');

Solution

  • Because require is not in scope in a function node (this applies to the file function node as well).

    See the doc for how to include extra modules: https://nodered.org/docs/writing-functions#loading-additional-modules

    Basically you need to add modules to the global context and include them from there.

    (P.S. the File function node has not been updated in over 4 years, the core function node has moved on a long way since then)