28

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?

rossanmol
  • 1,633
  • 3
  • 17
  • 34

3 Answers3

68
var configData = require('./../common/config.js');
  1. ./ is testing/

  2. ./../ is websites/

  3. ./../common/ is websites/common/

  4. ./../common/config.js is websites/common/config.js

ibrahim mahrir
  • 31,174
  • 5
  • 48
  • 73
8

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.

Dario
  • 3,905
  • 2
  • 13
  • 27
-1
const cheerio = require('../node_modules/cheerio');
const request = require('../node_modules/request-promise');
const vl = require('../node_modules/validator');
const crypto = require('crypto');
const fs = require('fs');
user956584
  • 5,316
  • 3
  • 40
  • 50
  • 4
    A good answer will always include an explanation why this would solve the issue, so that the OP and any future readers can learn from it. – Tyler2P Feb 05 '22 at 10:01