so i usually use ruby irb, and I can pull .rb files I wrote into the console environment by running
load './script.rb'
and then all of the functions I wrote in script.rb will be available.
I cannot figure out for the life of me how to do this in the node "console" environment!
You can load JavaScript files using the require function. The following example assume that the Node.js process was started at the directory where your file is located.
require('./script.js');
This will execute the contents of the file.
If you have exported functions or objects, you can assign them to a variable and use them later.
const myFunction = require('./script.js').myFunction;
myFunction();
Like many other development frameworks/languages, Node has a Modules/Package System which, is a CommonJS variant. To load a Module use require(). The usage of require() is the same when running JavaScript files or running in the REPL.
You can require Node Core Modules, NPM Installed Packages or your own local modules. When loading NPM Packages specified in a package.json or a local module, Node will load them from the Current Working Directory(CWD), you can check this using process.cwd(). The CWD will be set to the absolute path of the directory you launched the REPL from.
You can launch the REPL via running node in your CLI and require your packages like below.
// Core Package
const os = require('os')`
console.log(os)
// NPM Package
const moment = require('moment')
console.log(moment)
// Local Package
const myPackage = require('./myPackage')
console.log(myPackage)
You can also pre-require module(s) using the -r flag when running node. The below will launch the Node REPL with the os package preloaded. You can then access the os package using the variable os
node -r os
console.log(os)
In the future, Node may also support ECMAScript Modules (ie. import). You can read more detailed info about that in the Enhancement Proposal.
Related
I have a slight problem with a basic Node.JS method. When I'm trying to use "require()' method to import any downloaded (with 'npm install ..) module/library, I get a Visual Studio Code message that asks 'to convert 'require'(which is a Common JS module) into ES. If I do it, it transforms 'require()' into 'import..' though I want keep using 'require()'. Why is it so ? I read somewhere that Common JS is already included in the Node.JS environment though.
Then, when trying to compile my index.js file (with 'node index.js'), I obviously get an error about 'require' not recognized method.
Error [ERR_REQUIRE_ESM]: require() of ES Module C:\Users...index.js from C:\Users...index.js not supported.
I tried then to install Webpack to fix this issue, but nothing change. I also kind of installed CommonJS (npm i common-js)..
Another common answer was to remove 'type':'module' from package.json file which normally should allow to use 'require', but I don't even have such a line in the file.
On top of that I've recently read that 'require' is not compatible with browser development tools (it's ok). But I'm trying to import a downloaded module/npm package in VSC terminal, not even in a browser.
As you understand I'm new to Node.JS, but I don't really get what's going on in this case...
Currently I am playing around with electron using vue-cli-plugin-electron-builder along side a simple vue project. This is the project https://github.com/nklayman/vue-cli-plugin-electron-builder .
vue create my-project
cd my-project
vue add electron-builder
npm run electron:serve
My goal is to add a simple plugin-like architecture. The app serves only base functionality but can be extended with "plugins". Those plugins therefore are not included in the built, but will be loaded at runtime by electron. I would prefere when those plugins just behave like node modules ( module.exports = ) with its own dependencies ( probably with a package.json file inside ). I would locate those plugins at app.getPath('userData') + '/Plugins.
I looked at a few approaches on how to tackle this problem :
1. Using Nodejs vm module
First, I tried using Nodejs vm module to read and execute a script from an external file, all at runtime. It works great so far, although I would not be able to use external dependencies inside those loaded scripts. If I want to use external dependencies inside the plugin scripts, those dependencies must have been included in the electron build beforehand. Somehow defeats the whole purpose of having plugins ... only vanilla js + nodejs base modules would be possible .
2. using global.require
I saw this solution in another SO answer.
Using node require with Electron and Webpack
Webpack/electron require dynamic module
They say to use global.require but it throws an error saying global.require is not a function. The solution looked promising first, but somehow I can't get it to work.
3. simply use require
Of course I had to try it. When I try to require an external module from a non-project location it won't find the module, even if the path is correct. Again, the path I am trying to locate the module should be at app.getPath("userData"), not in the projects root directory. When however, I locate the plugins inside the root directory of the project it gets included in the built. This again defeats the purpose of having plugins.
Goal
So far, I haven't found a viable solution to this. I simply want my electron app to be extendible with basic node modules at runtime ( following a pre-defined schema to simplify ) . Of course there is atom, made with electron, using their own apm manager to install and load plugins, but this seems way to overpowered. Its enough for me to only have plugin files located locally, to have a public "marketplace" is no goal. Also, it's ok if the app has to reload / restart to load plugins.
Any ideas ?
After more and more research I stumbled over 2 packages :
https://www.npmjs.com/package/live-plugin-manager
https://github.com/getstation/electron-package-manager
both integrating npm to programmatically handle package installation at runtime. I settled for live-plugin-manager for now since its better documented and even allow package installation from local file system.
Pro
I was able to integrate the system out-of-the-box into a vanilla electron app. Works like a charm.
Cons
.I was not able to use it inside a vue electron boilerplate (like the one I said I was using in OP), since webpack is interferring with the require environment. But there sure is a solution to this.
Update : I was able to get it to work eventually inside a webpack bundled electron vue boilerplate. I accidentally mixed import and require . The following code works for me using live-plugin-manager
// plugin-loader.js
const path = require('path');
const { PluginManager } = require('live-plugin-manager');
const pluginInstallFolder = path.resolve(app.getPath('userData'), '.plugins');
const pluginManager = new PluginManager();
module.exports = async (pkg) => {
// installs pkg from npm
await pluginManager.install(pkg);
const package = pluginManager.require(pkg);
return package
}
// main.js
const pluginLoader = require('./plugin-loader');
pluginLoader("moment").then((moment) => {
console.log(moment().format());
})
This will install "moment" package from npm during runtime into a local directory and load it into the app, without bundling it into the executable files.
I have a project that depends on the websocket package. However, for node 10.x, the latest version (1.0.31) of websocket works, while on node 4.x version 10.0.24 works but the 10.0.31 does not. Is it possible to specify different package (versions) per nodejs version to handle cases like this, e.g. like so
node 4.x and older -> websockets 1.0.24
all other node versions -> websockets 1.0.31
Preferable it should work in both npm and yarn, but if it only works in either that's fine as well.
The node 10 version is used in dev setups, while the node 4.x is used in a legacy embedded platform that cannot run docker or be upgraded.
Consider utilizing a postinstall script in the scripts section of your projects package.json. For instance:
package.json
"scripts": {
"postinstall": "node install-websocket"
},
As you can see, the postinstall script invokes a nodejs script, arbitrarily named install-websocket.js.
install-websocket.js
const execSync = require('child_process').execSync;
const nodeMajorVersion = process.version.replace(/^v/, '').split('.')[0];
const websocketVersion = nodeMajorVersion <= '4' ? '1.0.24' : '1.0.31';
execSync('npm install websocket#' + websocketVersion, {
cwd: __dirname,
stdio: 'inherit'
});
The install-websocket.js script essentially performs the following tasks:
Gets the version of node.js using process.version which returns a string, e.g. v13.10.1
To obtain the Major version from that string (i.e. 13 in that aforementioned example) we use a combination of the replace() and split() methods.
The conditional (ternary) operator ascertains
which version of websocket to subsequently install - based on whether the value of nodeMajorVersion is <= 4.
Finally we "shell out" the appropriate npm install websocket#x.x.x command using execSync.
Note: If you're concerned about execSync being synchronous, then utilize the asynchronous exec instead.
Additional Notes:
Given the code shown above it assumes the install-websocket.js file resides in the root of your project directory, i.e. at the same level as package.json.
my-project
├── package.json
├── install-websocket.js
└── ...
It's important for the install-websocket.js file to exist at this location for following two reasons:
Primarily, and most importantly, because you'll have noticed that we specify __dirname for the value of execSync's cwd option. The value of __dirname in this context is the pathame to the parent directory of wherever the install-websocket.js file resides.
Essentially by setting the cwd option to this specific pathname, (i.e. the path to the project directory), we ensure that when the npm install websocket#x.x.x command is run it gets installed in the same location as where your project resides - regardless of whether it's installed locally or globally.
The postinstall script in package.json expects the install-websocket.js file to reside there too. Note how it currently runs; node install-websocket, and doesn't assume the file exists elsewhere, i.e. it's not running something like: node ./some/path/to/install-websocket
If consumers of your package have npm configured to ignore-scripts then websocket's simply will not be installed because the postinstall script will not be invoked.
When calling a node module directly, e.g. $ ./node_modules/.bin/webpack -d, how is the module aware of how to handle any require functions?
I understand how the require function works, but I'm confused where it is defined.
I had assumed that using something like $ npm start would give context to handle require, but how does Node get involved (and define how to handle require) when the module is called directly?
You're not calling the module directly, you're calling an executable that got installed as part of a package.
That executable runs a full Node interpreter, with the contents of the executable file as the script.
Basically, it's similar to running this on the command line:
node ./node_modules/.bin/webpack
Having started to work on node.js recently, I am trying to use rename package. Successfully installed (npm install rename) package and sample code (residing in file test.js) is pasted below:
console.log('Starting to rename');
var rename = require('rename');
rename('a.js', 'b.js');
console.log('Rename done');
The file a.js resides in the same directory as test.js. The console shows the two debug messages correctly, but the file a.js is not renamed.
How can I enable debug on rename module (or for that matter any node module), so that I can debug it additional log messages?
Note: Other packages like find, mkdirp, etc are working fine.
You can enable debug by doing a DEBUG=* node app.js or passign env variable DEBUG with wildcard * . It would enable debug for all modules, provided the module you wish to debug is actually using debug.
Hardcore way of doing is to make local changes in the module.