You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node-RED导入现有JS库及调用全局对象的技术咨询

Hey there! Since you're new to Node-RED and Node.js, let's break this down step by step—this is actually a common scenario when moving from front-end jQuery projects to building backend APIs with Node-RED.

How to Import Existing JS Libraries & Create Globally Accessible Objects in Node-RED

1. Importing Your Existing JS Files

You have two main ways to bring in your JS library, depending on whether you want it available in a single Function node or across all nodes in your flow.

Option A: Local Import (Per Function Node)

Node-RED's Function node supports standard Node.js require() calls, just like regular Node.js code.

  • If your library is a local file (e.g., my-auth-library.js), place it in Node-RED's user directory (usually ~/.node-red on Linux/macOS, or %USERPROFILE%\.node-red on Windows).
  • Then in your Function node, import it like this:
    // Import the local library
    const authLib = require('./my-auth-library.js');
    
    // Use it in your logic
    const isValidUser = authLib.validateCredentials(msg.payload.username, msg.payload.password);
    msg.payload = { success: isValidUser };
    return msg;
    
  • If your library is an npm package, first install it in Node-RED's user directory via terminal:
    cd ~/.node-red
    npm install your-package-name
    
    Then import it the same way: const authLib = require('your-package-name');

Option B: Global Import (All Function Nodes)

If you want your library accessible everywhere in your Node-RED instance, configure it in the settings.js file:

  1. Open settings.js (located in your Node-RED user directory).
  2. Find the functionGlobalContext section, uncomment it, and add your library:
    functionGlobalContext: {
        // Import local file
        authLib: require('./my-auth-library.js'),
        // Or an npm package
        jwt: require('jsonwebtoken')
    },
    
  3. Restart Node-RED to apply the changes.
  4. Now in any Function node, access it using global.get():
    const authLib = global.get('authLib');
    const sessionToken = authLib.generateToken(msg.payload.userId);
    msg.payload = { token: sessionToken };
    return msg;
    

2. Calling Library Functions & Creating Global Objects

Calling Library Functions

Once you've imported the library, calling its functions works exactly like you'd expect in regular JS. For example, if your library has a login() function:

// Local import example
const authLib = require('./my-auth-library.js');
const loginResult = authLib.login(msg.payload.username, msg.payload.password);

// Global import example
const authLib = global.get('authLib');
const logoutSuccess = authLib.logout(msg.payload.token);

Creating Globally Accessible Objects

If you need an object (like a session manager or config store) to be available across all nodes, use Node-RED's global context:

  1. Initialize the object in a Function node (maybe a "Start" node that runs once on flow deploy):
    const authLib = global.get('authLib');
    // Create your global object
    const sessionManager = authLib.createSessionStore();
    // Save it to global context
    global.set('sessionManager', sessionManager);
    
  2. Then in any other Function node, retrieve and use it:
    const sessionManager = global.get('sessionManager');
    const userSession = sessionManager.getSession(msg.payload.token);
    msg.payload = { user: userSession };
    return msg;
    

Note: By default, global context uses in-memory storage—so your objects will reset if Node-RED restarts. If you need persistent storage, you can configure context storage in settings.js (look for the contextStorage section).

Quick Tips for Your Login/Logout API

  • For your HTTP In nodes listening to POST requests, connect them to Function nodes where you'll use your library to handle authentication logic.
  • If your library uses asynchronous functions (like database calls), use async/await in your Function node to handle them properly:
    async function handleLogin(msg) {
        const authLib = global.get('authLib');
        // Await the async login function
        const loginResult = await authLib.asyncLogin(msg.payload.username, msg.payload.password);
        msg.payload = loginResult;
        return msg;
    }
    return handleLogin(msg);
    

内容的提问来源于stack exchange,提问作者Vladimir B

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 04:03:52