Skip to content

Using Node.js modules

Phil Beauvoir edited this page Feb 22, 2024 · 11 revisions

Using Node.js (CommonJS) modules in your jArchi script

Note

Since jArchi 1.6 you can access your own modules or other CommonJS modules. There is an option in Archi's Scripting Preferences to enable/disable CommonJS support if you wish.

  • By "Node.js" modules we mean CommonJS modules. So a module doesn't have to be specifically written for Node.js: as soon as it respects CommonJS specification, it should be usable.
  • Not all modules will work within Archi because Archi doesn't implement core/native/builtin (call them whatever you want) modules. A rule of thumb: the less dependencies a module has, the higher the chance it will be usable.
  • Archi doesn't come with npm, so if you want to reuse real Node.js modules, you will have either to install Node.js and npm on your workstation and make sure it downloads modules at the right place. You can also download modules manually (only doable for modules with no, or really few, dependencies)

Loading a CommonJS file in your script

You can reference a CommonJS object using require like this:

const myVar = require(__DIR__ + "module.js");

This is different to the usual load command:

load(__DIR__ + "file.js");
  • load() works with local or remote content
  • require() works with local content only
  • require("moduleName") will look for a module stored under node_modules/moduleName (which is assumed to contain a CommonJS module, which can be as simple as a single index.js file or contain much more than that)
  • require("Path/To/Some/File.js") will load File.js assuming it is a "self contained" CommonJS module

A simple example:

  1. In your jArchi scripts folder create a sub-folder named node_modules. This is the parent folder for node modules.
  2. In the node_modules folder create a sub-folder named helloworld. This will be the folder for your module.
  3. In the helloworld folder create a file called index.js containing this code:
exports.sayHelloWorld = function() {
    window.alert("Hello World!");
}
  1. In your jArchi scripts folder create a file called test_module.ajs containing this code:
const speaker = require("helloworld");
speaker.sayHelloWorld();
  1. Run the test_module.ajs script