I have the following structure:
-- node_modules
-- websites
---- common
------- config.js
---- testing
------- test.js
Inside config I have some variables set, which are being exported using module.export.
I am trying to retrieve those variables when running node test.js
from config.js using the following codes:
var configData = require('./common/config.js')
var configData = require('../common/config.js')
None of them work. What can I do to retrieve the data from the other folder?
In NodeJS, require() is a built-in function to include external modules that exist in separate files. require() statement basically reads a JavaScript file, executes it, and then proceeds to return the export object.
Node. js follows the commonJS module system, and it require to include modules that exist in separate files and for that purpose it has methods like “require” and “ES6 import and export” are available in node.
This function takes a path (in the form of a string) and strips it of duplicate slashes and normalizes directory abbreviations, like '.' for 'this directory' and '..' for 'one level up'. For example: > var path = require('path'); > path.normalize('/a/.///b/d/../c/') '/a/b/c/'
You can use __dirname to check on which directories your files live. Create and edit controller.js in the api subdirectory in the src directory: src/api/controller.js. log(__dirname) // "/Users/Sam/dirname-example/src/api" console.
var configData = require('./../common/config.js');
./
is testing/
./../
is websites/
./../common/
is websites/common/
./../common/config.js
is websites/common/config.js
from test.js:
const configData = require('../common/config');
You can safely omit '.js'
.
As documentation say:
File Modules
If the exact filename is not found, then Node.js will attempt to load the required filename with the added extensions: .js, .json, and finally .node.
.js files are interpreted as JavaScript text files, and .json files are parsed as JSON text files. .node files are interpreted as compiled addon modules loaded with dlopen.
A required module prefixed with '/' is an absolute path to the file. For example, require('/home/marco/foo.js') will load the file at /home/marco/foo.js.
A required module prefixed with './' is relative to the file calling require(). That is, circle.js must be in the same directory as foo.js for require('./circle') to find it.
Without a leading '/', './', or '../' to indicate a file, the module must either be a core module or is loaded from a node_modules folder.
If the given path does not exist, require() will throw an Error with its code property set to 'MODULE_NOT_FOUND'.
More info about how require()
work here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With