How do I require JS files within the same directory properly? - javascript

I'm having trouble understanding how require() works in JS.
Here's the issue I'm having:
My folder structure looks like this:
test
->test
->a.js
->b.js
->c.js
And here is the code I have in each file:
In c.js:
function c() {
console.log("c")
}
module.exports = c;
In b.js:
let c = require("./c");
function b() {
c();
console.log("b");
}
exports.b = b;
In a.js:
let b = require("./test/b")
When I execute the code in a.js, it runs fine.
But when I execute the code in b.js it throws an error:
module.js:472
throw err;
^
Error: Cannot find module './c'
at Function.Module._resolveFilename (module.js:470:15)
at Function.Module._load (module.js:418:25)
at Module.require (module.js:498:17)
at require (internal/module.js:20:19)
at [stdin]:3:9
at ContextifyScript.Script.runInThisContext (vm.js:23:33)
at Object.runInThisContext (vm.js:95:38)
at Object.<anonymous> ([stdin]-wrapper:6:22)
at Module._compile (module.js:571:32)
at evalScript (bootstrap_node.js:391:27)
But when I change the contents of b.js to be:
let c = require("./test/c");
function b() {
c();
console.log("b");
}
module.exports = b;
Now a.js throws an error:
module.js:472
throw err;
^
Error: Cannot find module './test/c'
at Function.Module._resolveFilename (module.js:470:15)
at Function.Module._load (module.js:418:25)
at Module.require (module.js:498:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (/Users/sp/Desktop/test/test/b.js:1:71)
at Module._compile (module.js:571:32)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3)
What am I not understanding?

I assume you're running them all from /test/ root directory.
Running a.js from root: ./test/b points to /test/test/b
Running b.js from root: ./c points to /test/c which does not exist.
When you run a.js from root, it requires b.js from ./test/b which then requires c.js going the relative path from its own directory via ./c - that's why it's working if you run a.js.
Now running b.js from upper /test/ directory results in b.js looking for c.js in /test/c instead of /test/test/c.
Changing b.js to let c = require("./test/c"); leads to the following:
a.js still requires b.js from ./test/b aka /test/test/b. Now b.js tries to require from ./test/c pointing to non existent /test/test/test/c.

Node looks for a module object from a file it require()s. Specifically looking at module.exports
// File a.js
const foo = "Hello"
module.exports = foo
 
// File b.js
const bar = "World"
module.exports = bar
 
// File index.js
const a = require('./a')
const b = require('./b')
console.log(a, b) //Hello World
You can also export objects
module.exports = { foo, bar }
Which you import like this
const { foo, bar} = require("./file")
And when you don't specify a location, it looks in node_modules
const express = require('express') // Looks inside node_modules for express

Related

Mindee API throws error- Error: Cannot find module 'node:buffer'

I was exploring Mindee to make a code that converts the pdf to text, so I followed the steps and used the code from the documentation, but when I run it with node it throws this error:
internal/modules/cjs/loader.js:883
throw err;
^
Error: Cannot find module 'node:buffer'
Require stack:
- C:\Users\budgi\OneDrive\Documentos\TrabajosBi\Proy\Fedex\v2\node_modules\mindee\src\inputs\sources.js
- C:\Users\budgi\OneDrive\Documentos\TrabajosBi\Proy\Fedex\v2\node_modules\mindee\src\inputs\index.js
- C:\Users\budgi\OneDrive\Documentos\TrabajosBi\Proy\Fedex\v2\node_modules\mindee\src\client.js
- C:\Users\budgi\OneDrive\Documentos\TrabajosBi\Proy\Fedex\v2\node_modules\mindee\src\index.js
- C:\Users\budgi\OneDrive\Documentos\TrabajosBi\Proy\Fedex\v2\app.js
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:880:15)
at Function.Module._load (internal/modules/cjs/loader.js:725:27)
at Module.require (internal/modules/cjs/loader.js:952:19)
at require (internal/modules/cjs/helpers.js:88:18)
at Object.<anonymous> (C:\Users\budgi\OneDrive\Documentos\TrabajosBi\Proy\Fedex\v2\node_modules\mindee\src\inputs\sources.js:30:23)
at Module._compile (internal/modules/cjs/loader.js:1063:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
at Module.load (internal/modules/cjs/loader.js:928:32)
at Function.Module._load (internal/modules/cjs/loader.js:769:14)
at Module.require (internal/modules/cjs/loader.js:952:19) {
code: 'MODULE_NOT_FOUND',
requireStack: [
'C:\\Users\\budgi\\OneDrive\\Documentos\\TrabajosBi\\Proy\\Fedex\\v2\\node_modules\\mindee\\src\\inputs\\sources.js',
'C:\\Users\\budgi\\OneDrive\\Documentos\\TrabajosBi\\Proy\\Fedex\\v2\\node_modules\\mindee\\src\\inputs\\index.js',
'C:\\Users\\budgi\\OneDrive\\Documentos\\TrabajosBi\\Proy\\Fedex\\v2\\node_modules\\mindee\\src\\client.js',
'C:\\Users\\budgi\\OneDrive\\Documentos\\TrabajosBi\\Proy\\Fedex\\v2\\node_modules\\mindee\\src\\index.js',
'C:\\Users\\budgi\\OneDrive\\Documentos\\TrabajosBi\\Proy\\Fedex\\v2\\app.js'
]
}
These are the folders:
folders
And the app.js (pasted the code from the documentation)
const mindee = require("mindee");
// for TS or modules:
// import * as mindee from "mindee";
// Init a new client
const mindeeClient = new mindee.Client({apiKey: "1234567890"});
// Load a file from disk and parse it
const invoiceResponse = mindeeClient
.docFromPath("/path/to/the/invoice.pdf")
.parse(mindee.InvoiceV3);
// Print a the parsed data
invoiceResponse.then((resp) => {
// The document property can be undefined:
// * TypeScript will throw an error without this guard clause
// (or consider using '?' notation)
// * JavaScript will be very happy to produce subtle bugs
// without this guard clause
if (resp.document === undefined) return;
// full object
console.log(resp.document);
// string summary
console.log(resp.document.toString());
});
What can be the cause of the error?

Error: Cannot find module 'config' at Function.Module._resolveFilename

Hii I have simple node server, with the following structure
myapp
-config
-default-json
-index.js
-package-lock.json
-package.json
Here is my part of my index.js
'use strict';
const
config = require('config'),
express = require('express'),
request = require('request'),
body_parser = require('body-parser'),
app = express().use(body_parser.json()); // creates express http server
// Sets server port and logs message on success
app.listen(process.env.PORT || 1337, () => console.log('webhook is listening'));
when I run node index.js I get the following error
internal/modules/cjs/loader.js:583
throw err;
^
Error: Cannot find module 'config'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:581:15)
at Function.Module._load (internal/modules/cjs/loader.js:507:25)
at Module.require (internal/modules/cjs/loader.js:637:17)
at require (internal/modules/cjs/helpers.js:22:18)
at Object.<anonymous> (C:\xampp\htdocs\chat\index.js:13:14)
at Module._compile (internal/modules/cjs/loader.js:689:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
at Module.load (internal/modules/cjs/loader.js:599:32)
at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
at Function.Module._load (internal/modules/cjs/loader.js:530:3)
what is wrong with my code?
I found solution by by installing config from npm
https://www.npmjs.com/package/config
follow the instruction above and it should work , it might help some one in future
You have to explicitly add the config module in your package.json:
"dependencies": {
"config": "version number"
}
https://www.npmjs.com/package/config
It means there is no config.js in your current location. Put the exact location of the config.js file..
Try,
config = require('./config/config'),

jQuery not defined using mocha for testing wordpress javascript

I've set up mocha to run tests in the terminal. It works for basic test like expect(1).to.equal(1). The problem I run into is that my script is wrapped in the jQuery like so jQuery( function( $ ) { // my code here }); and I get an error when running the tests.
evalmachine.<anonymous>:15
jQuery( function ( $ ) {
^
ReferenceError: jQuery is not defined
at evalmachine.<anonymous>:15:1
at Object.exports.runInThisContext (vm.js:54:17)
at Suite.<anonymous> (/Users/grahamlutz/Documents/BBC/poolproof/test/test.js:21:8)
at context.describe.context.context (/usr/local/lib/node_modules/mocha/lib/interfaces/bdd.js:47:10)
at Object.<anonymous> (/Users/grahamlutz/Documents/BBC/poolproof/test/test.js:8:1)
at Module._compile (module.js:413:34)
at Object.Module._extensions..js (module.js:422:10)
at Module.load (module.js:357:32)
at Function.Module._load (module.js:314:12)
at Module.require (module.js:367:17)
at require (internal/module.js:16:19)
at /usr/local/lib/node_modules/mocha/lib/mocha.js:220:27
at Array.forEach (native)
at Mocha.loadFiles (/usr/local/lib/node_modules/mocha/lib/mocha.js:217:14)
at Mocha.run (/usr/local/lib/node_modules/mocha/lib/mocha.js:469:10)
at Object.<anonymous> (/usr/local/lib/node_modules/mocha/bin/_mocha:404:18)
at Module._compile (module.js:413:34)
at Object.Module._extensions..js (module.js:422:10)
at Module.load (module.js:357:32)
at Function.Module._load (module.js:314:12)
at Function.Module.runMain (module.js:447:10)
at startup (node.js:141:18)
at node.js:933:3
my test.js looks like this:
var assert = require('assert');
var chai = require('chai');
var expect = chai.expect;
var fs = require('fs');
var vm = require('vm');
var jsdom = require('mocha-jsdom');
describe('mocha tests', function () {
jsdom();
before(function () {
$ = require('jquery');
});
var path = __dirname + '/../wp-content/themes/bb-theme-child/myscript.js';
var code = fs.readFileSync(path);
vm.runInThisContext(code);
describe('getSession', function() {
it('should return the empty string because it fails', function () {
applyCoupon();
});
});
});
My question is either why is jQuery undefined or what incorrect assumptions am I making? Do I need to change the way I think about testing javascript within a wordpress set up?
The following two lines worked for me. For convenience I just put these at the top of my mocha test file. I used 'jsdom-global' package instead of 'mocha-jsdom' per the recommendation on the mocha-jsdom github readme. https://github.com/rstacruz/jsdom-global
this.jsdom = require('jsdom-global')()
global.$ = global.jQuery = require('jquery');
You have to export $ and jQuery to the global space yourself:
before(function () {
global.$ = global.jQuery = require('jquery');
});
If you read mocha-jsdom's documentation you'll see that it puts in the global space symbols like window and document. When you load jquery, it finds window and adds itself as window.$. In a browser, this also makes $ visible in the global space because window is the global space. In Node, however, the global space is global, and so you have to put $ in it yourself.

Requiring other files in node

I'm trying to require another file within a node project I'm working on; this will be a command line tool. What I'm trying to do is create a formatted color output using the following file format.js:
modules.exports = {
warning: function(input){
say("\033[31m" + input)
},
info: function(input){
say("\033[36m" + input)
}
}
From there I want to create the colored output and put it into a file named gen_email.js. That file has these two functions in it:
function say(input){
console.log(input)
}
function helpPage(){
say('');
format.info("test")
}
When I attempt to run this it outputs the following:
C:\Users\thomas_j_perkins\bin\javascript\node\email\lib\format.js:1
(function (exports, require, module, __filename, __dirname) { modules.exports = {
^
ReferenceError: modules is not defined
at Object.<anonymous> (C:\Users\thomas_j_perkins\bin\javascript\node\email\lib\for
mat.js:1:63)
at Module._compile (module.js:409:26)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Module.require (module.js:353:17)
at require (internal/module.js:12:17)
at Object.<anonymous> (C:\Users\thomas_j_perkins\bin\javascript\node\email\gen_ema
il.js:3:16)
at Module._compile (module.js:409:26)
at Object.Module._extensions..js (module.js:416:10)
I'm not understanding what I'm doing wrong, according to this I am requiring the file the correct way. What am I doing wrong here, do I need to move the say function into the other file?
It should be
module.exports = {
warning: function(input){
say("\033[31m" + input)
},
info: function(input){
say("\033[36m" + input)
}
}
in the other file
const format = require("whatEverPathIsOn/format.js")
if the file is under the same path just
const format = require("./format.js")
That should be module, not modules.

Javascript Require

include.js file contain
var test = function(){
console.log("log from included file");
};
main.js file contain
require('./include.js');
test();
when i tried to run main.js using node main.js command it shows
module.js:340
throw err;
^
Error: Cannot find module 'include.js'
at Function.Module._resolveFilename (module.js:338:15)
at Function.Module._load (module.js:280:25)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at Object.<anonymous> (d:\Nishada\test\main.js:1:63)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
what is the reason for this error ?
The error refers to a file not being found, make sure your file is in the same directory as main.js and try:
include.js
module.exports = {
test: function(){
console.log("log from included file");
}
}
main.js
var myInclude = require('include.js');
myInclude.test();
You will need to export the test function in order to use it in main.js
var test = function(){
console.log("log from included file");
};
module.exports = test
And in main.js add require as follows
require('./include.js'); // assuming include.js is in same directory as main.js
If you do require('include.js') then node will search include in global packages
You will have to give relative path of include.js while require.
If both are in same directory write it like bellow
var include = require('./include.js');
include.test();
and from include.js you can define them as function for exports
exports.test = function(){
console.log("log from included file");
};
Even Better
export just one object having multiple functions from include.js instead of exporting each separate function.
Like bellow
include.js
exports.test = obj;
obj.func1 = function(){};
obj.func2 = function(){};
main.js
var test = require('./include.js').test;
test.func1();
test.func2();

Categories

Resources