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.
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-redon Linux/macOS, or%USERPROFILE%\.node-redon 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:
Then import it the same way:cd ~/.node-red npm install your-package-nameconst 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:
- Open
settings.js(located in your Node-RED user directory). - Find the
functionGlobalContextsection, uncomment it, and add your library:functionGlobalContext: { // Import local file authLib: require('./my-auth-library.js'), // Or an npm package jwt: require('jsonwebtoken') }, - Restart Node-RED to apply the changes.
- 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:
- 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); - 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 thecontextStoragesection).
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/awaitin 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

