Trying to call nodejs from the exec node

I have a script that is created using nodejs. There are 2 modules being called pdf-merger-js and pdf-page-counter.

The script simple read the PDF and give me a page count. If the count is odd it add a blank page.

import * as fs from 'fs';
import PDFMerger from "file:///D:/Program%20Files/nodejs/node_modules/pdf-merger-js/index.js";
import pdf from "file:///D:/Program%20Files/nodejs/node_modules/pdf-page-counter/index.js";

var merger = new pdfMerger();

const pathtoblank = 'E:/PP_Processes/HR/BlankPdfPage/Blank.pdf';

var pathtopdf = msg.PathToFile;
var pathtooutput = msg.PathToOutput;

(async () => {
    let dataBuffer = fs.readFileSync(pathtopdf);
    console.log(pathtopdf);
    pdf(dataBuffer).then(async function (data) {
        // number of pages
        console.log(data.numpages);
        await merger.add(pathtopdf);
        if (data.numpages % 2 > 0) {
            await merger.add(pathtoblank);
        }
        await merger.save(pathtooutput);
    })
})();

Can I run nodejs from node-red?

You should be able to this all inside node-red. No need to spawn it. Function node can add the modules. File nodes can read the file data.

I tried pasting this script in a function node and I get a error "Cannot use import statement outside a module"

That's because it is not permitted. You make imports using the setup tab

See this blog post: Use any npm module in Node-RED • FlowFuse

1 Like

I am new to node-red. I tried the example provided in the video and now when I click the inject node. Node-Red just shutdown. I included the workflow below.

[
    {
        "id": "709799acea2e533f",
        "type": "tab",
        "label": "Flow 5",
        "disabled": false,
        "info": "",
        "env": []
    },
    {
        "id": "f6fc50ee2b18a97a",
        "type": "inject",
        "z": "709799acea2e533f",
        "name": "",
        "props": [
            {
                "p": "payload"
            }
        ],
        "repeat": "",
        "crontab": "",
        "once": false,
        "onceDelay": 0.1,
        "topic": "",
        "payload": "",
        "payloadType": "date",
        "x": 140,
        "y": 140,
        "wires": [
            [
                "d074323f939f8f39"
            ]
        ]
    },
    {
        "id": "6d65cc020fa74fca",
        "type": "function",
        "z": "709799acea2e533f",
        "name": "paddthembaby",
        "func": "//import * as fs from 'fs';\n//import PDFMerger from \"file:///D:/Program%20Files/nodejs/node_modules/pdf-merger-js/index.js\";\n//import pdf from \"file:///D:/Program%20Files/nodejs/node_modules/pdf-page-counter/index.js\";\n\nvar fs = fs;\nvar merger = new pdfMerger();\n\nconst pathtoblank = 'E:/PP_Processes/HR/BlankPdfPage/Blank.pdf';\n\nvar pathtopdf = msg.PathToFile;\nvar pathtooutput = msg.PathToOutput;\n\n(async () => {\n    let dataBuffer = fs.readFileSync(pathtopdf);\n    console.log(pathtopdf);\n    pdf(dataBuffer).then(async function (data) {\n        // number of pages\n        console.log(data.numpages);\n        await merger.add(pathtopdf);\n        if (data.numpages % 2 > 0) {\n            await merger.add(pathtoblank);\n        }\n        await merger.save(pathtooutput);\n    })\n})();",
        "outputs": 1,
        "timeout": 0,
        "noerr": 0,
        "initialize": "\n",
        "finalize": "",
        "libs": [
            {
                "var": "fs",
                "module": "fs"
            },
            {
                "var": "pdfMerger",
                "module": "pdf-merger-js"
            },
            {
                "var": "pdf",
                "module": "pdf-page-counter"
            }
        ],
        "x": 920,
        "y": 180,
        "wires": [
            [
                "93892fe06ea34413"
            ]
        ]
    },
    {
        "id": "bd2f9238b82802c8",
        "type": "function",
        "z": "709799acea2e533f",
        "name": "function 56",
        "func": "var today = new Date();\nvar dd = String(today.getDate()).padStart(2, '0');\nvar mm = String(today.getMonth() + 1).padStart(2, '0'); //January is 0!\nvar yyyy = today.getFullYear();\n\nmsg.PathToFile = msg.payload\nvar backslash = '\\\\';\nmsg.filename = msg.payload.slice(msg.payload.lastIndexOf(\"\\\\\")+1);\nmsg.PathToBackup = \"E:\\\\PP_DATA_COPY_EXCH\\\\Human_Resources\\\\Posters\\\\Archive\\\\Backup\" + \"\\\\\" + yyyy + \"\\\\\" + mm + \"\\\\\" + dd + \"\\\\\" + msg.filename;\nmsg.PathtoOutput = \"E:\\\\PP_DATA_COPY_EXCH\\\\Human_Resources\\\\Posters\\\\Padded\\\\\" + msg.filename;\n\nreturn msg;",
        "outputs": 1,
        "timeout": 0,
        "noerr": 0,
        "initialize": "",
        "finalize": "",
        "libs": [],
        "x": 670,
        "y": 140,
        "wires": [
            [
                "8d1289164f51b01f",
                "6d65cc020fa74fca"
            ]
        ]
    },
    {
        "id": "d074323f939f8f39",
        "type": "olfnf-folder-listing",
        "z": "709799acea2e533f",
        "folder": "E:\\PP_DATA_COPY_EXCH\\Human_Resources\\Posters\\In",
        "folder_type": "str",
        "subfolder": false,
        "ignoreempty": true,
        "masks": "*.*",
        "masksregex": false,
        "name": "",
        "x": 330,
        "y": 140,
        "wires": [
            [
                "42b75d085f92e9e9",
                "6876cb2dac7f5af8"
            ]
        ]
    },
    {
        "id": "42b75d085f92e9e9",
        "type": "debug",
        "z": "709799acea2e533f",
        "name": "debug 25",
        "active": true,
        "tosidebar": true,
        "console": false,
        "tostatus": false,
        "complete": "payload",
        "targetType": "msg",
        "statusVal": "",
        "statusType": "auto",
        "x": 430,
        "y": 240,
        "wires": []
    },
    {
        "id": "8d1289164f51b01f",
        "type": "debug",
        "z": "709799acea2e533f",
        "name": "debug 26",
        "active": true,
        "tosidebar": true,
        "console": false,
        "tostatus": false,
        "complete": "true",
        "targetType": "full",
        "statusVal": "",
        "statusType": "auto",
        "x": 700,
        "y": 80,
        "wires": []
    },
    {
        "id": "6876cb2dac7f5af8",
        "type": "split",
        "z": "709799acea2e533f",
        "name": "",
        "splt": "\\n",
        "spltType": "str",
        "arraySplt": 1,
        "arraySpltType": "len",
        "stream": false,
        "addname": "",
        "x": 510,
        "y": 140,
        "wires": [
            [
                "bd2f9238b82802c8"
            ]
        ]
    },
    {
        "id": "93892fe06ea34413",
        "type": "debug",
        "z": "709799acea2e533f",
        "name": "debug 28",
        "active": true,
        "tosidebar": true,
        "console": false,
        "tostatus": false,
        "complete": "true",
        "targetType": "full",
        "statusVal": "",
        "statusType": "auto",
        "x": 1160,
        "y": 120,
        "wires": []
    }
]

Any help with this would be greatly appreciated.

There is a node-red node available for merging pdf's. (under the hood it uses pdf merger).

if the node suggested by @bakman2 is not what you need, then the function should be something like this:

try {
    const merger = new pdfMerger();
    const myPDF = await pdf(msg.payload) // load the PDF
    if (myPDF.numpages % 2 > 0) {
        await merger.add(msg.filename) // add input file
        await merger.add(msg.blankfile); // add blank
        const uint8Data = await merger.saveAsBuffer()
        msg.payload = Buffer.from(uint8Data)
    } 
    return msg
} catch (error) {
    node.error(error, msg);
}

Demo flow

[{"id":"f6fc50ee2b18a97a","type":"inject","z":"709799acea2e533f","name":"filename: c:/temp/test.pdf","props":[{"p":"filename","v":"c:/temp/test.pdf","vt":"str"},{"p":"blankfile","v":"c:/temp/blank.pdf","vt":"str"},{"p":"output","v":"c:/temp/new.pdf","vt":"str"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","x":610,"y":380,"wires":[["5de94974c86d10da"]]},{"id":"ec03b3fd42260fee","type":"function","z":"709799acea2e533f","name":"add a blank if page count is odd","func":"try {\n    const merger = new pdfMerger();\n    const myPDF = await pdf(msg.payload) // load the PDF\n    if (myPDF.numpages % 2 > 0) {\n        await merger.add(msg.filename) // add input file\n        await merger.add(msg.blankfile); // add blank\n        const uint8Data = await merger.saveAsBuffer()\n        msg.payload = Buffer.from(uint8Data)\n    } \n    return msg\n} catch (error) {\n    node.error(error, msg);\n}\n","outputs":1,"timeout":0,"noerr":0,"initialize":"\n","finalize":"","libs":[{"var":"fs","module":"fs"},{"var":"pdfMerger","module":"pdf-merger-js"},{"var":"pdf","module":"pdf-page-counter"}],"x":1170,"y":380,"wires":[["1253911e6cdf737c","b847ab30e54ae8da"]]},{"id":"5de94974c86d10da","type":"file in","z":"709799acea2e533f","name":"","filename":"filename","filenameType":"msg","format":"","chunk":false,"sendError":false,"encoding":"none","allProps":false,"x":840,"y":380,"wires":[["148db3d792ce9fc1","ec03b3fd42260fee"]]},{"id":"148db3d792ce9fc1","type":"debug","z":"709799acea2e533f","name":"look at me - i am the pdf file data","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"payload","targetType":"msg","statusVal":"","statusType":"auto","x":910,"y":460,"wires":[]},{"id":"1253911e6cdf737c","type":"debug","z":"709799acea2e533f","name":"merged (or original)","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"payload","targetType":"msg","statusVal":"","statusType":"auto","x":1200,"y":460,"wires":[]},{"id":"b847ab30e54ae8da","type":"file","z":"709799acea2e533f","name":"","filename":"output","filenameType":"msg","appendNewline":true,"createDir":false,"overwriteFile":"false","encoding":"none","x":1470,"y":380,"wires":[[]]}]

Result

Thank you for your help.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.