Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to require a .js file in node repl

Tags:

node.js

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!

like image 826
Brock Tillotson Avatar asked Nov 26 '25 05:11

Brock Tillotson


2 Answers

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 image 100
Tsvetan Ganev Avatar answered Nov 28 '25 19:11

Tsvetan Ganev


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.

like image 24
peteb Avatar answered Nov 28 '25 17:11

peteb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!