Use of fs as a global module (best practice )

I am after some advice on best/appropriate practice. I am using the fantastic node-red-contrib-google-oauth2 node to connect to the google APIs to upload files to google drive.

The v3 of the drive API requires that a ReadStream rather than a buffer be used for content upload.

I have loaded the fs module as a global module in the settings.js

  functionGlobalContext: {
        fs:require('fs'),
    },

and then use it it in the function node preparing the API call.

const fs = global.get('fs')

let fileMetadata = {
    name : msg.filenameShort,
}

let media = {
    mimeType : 'application/x-tar',
    body :  fs.createReadStream(msg.filename)
}

msg.payload = {
    resource : fileMetadata,
    media : media,
    fields : 'id'
}

return msg

Is this an apprpriate use of global modules or is there a better way to achieve this ?

Thanks

I also use it exactly in the same way

1 Like

Hi @chrisn-au,
I think that in the next 1.3 version (which will be released soon), you won't need to manually edit the settings.js file anymore: see this pull-request.
Bart

Bart, thanks Looking forward to 1.3 especially being able to package subflows as npm modules

2 Likes

Also worth noting that Node-RED makes extensive use of fs-extra which I also use in uibuilder since it provides some really useful features over and above the standard fs but is also fully backward compatible. What it means though is that fs-extra is already loaded so using it doesn't add any extra overheads.

@TotallyInformation That is interesting thanks - How do I access fs-extra. Is it exposed as a global ?

Hi, no, it is just another module so reference it in the normal way. You will need to include it in your package.json so just install in the normal fashion and let npm and node.js take care of the details. This is one of the strengths of node.js (when it gets it right, it can occasionally go spectacularly wrong for a variety of reasons but it mostly works and I've had no issues with fs-extra).

1 Like

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