Unable to import from a relative path using node js - node.js

Currently my automation framework built on Cucumber+ Nodejs+ webdriverio. It has the following structure for data files
main/
..../data
......../region1.js
......../region2.js
In my step definition I need to import the data files so that my functions can use the data as per the region I intend to execute which I provide during run time
How should I mention my import command? for example, I tried the following but that does not work
import users from '../main/data/*';

Posting a solution which I came across
Step 1: Add an index.js file under /data folder
Step 2: Adding the following code in index.js
import * as region1 from "../region1"
import * as region2 from "../region2"
export {
region1,
region2
}
Now in the file that requires this data, add the following import line
import myValues from "./main/data"
You need to pass your required region from command line as an environment variable lets say as REGION
If you want to access a value from respective region file based on value passed in REGION, the following code will work
const myreqData = myValues[process.env.REGION].<respective node in the js]

Related

NodeJS `"imports"` field on `package.json` for more than 1 file-tree level

I try to convert some references on my node projects to Node 19. In particular, the feature "imports" on the file package.json made me wonder on how to import files with an alias.
Example: For a project with source folder src with folders fruits and vegetables, I add the configuration on json content first-order key-values.
"imports": {
"#fruits/*": "./src/fruits/*.js",
"#fruits/*.js": "./src/fruits/*.js",
"#vegetables/*": "./src/vegetables/*.js",
"#vegetables/*.js": "./src/vegetables/*.js",
},
With that, I am able to use import * from "#fruits/fruits.js" or import * from "#vegetables/vegetables.js"
By experience, I learned that I cannot user it more than 1 level of folder-tree level. It means, in case there is still a folder src/fruits/pseudo, I am unable to use import * from "#fruits/pseudo/pseudofruits.js". Is this correct or should I be able to import pseudofruits from the alias?
Your understanding is correct that you can only import files one level deep with configuration you have. One workaround in this situation is to use the relative path instead like:
import * as pseudofruits from "../../fruits/pseudo/pseudofruits.js";

importing a function defined in a different directory

Disclaimer: I am studying Python. I am given a task of reusing functions.
the function is simple:
app/utils/calculators.py
def calculate_session(session_type, session_code):
return 3 # just to save space
Now i need to use the function from a different file but for the life of me, I failed to import it. I have already added init.py to utils directory, to the app directory as well.
app/tasks/process_sessions.py
from utils.calculators import calculate_session
but when I run it, it fails saying module not found. I am in a virtual environment and all the files go in app directory.
What am I missing?
You'll want to specify the full path of the file (including the root directory) and import the specific function. Example below:
from app.utils.calculators import calculate_session
This should then import your function, regardless of whether you're using a virtual environment.

ImportError: No module named functions

Image
I don't know what am I doing wrong here. I am importing the module from the functions package in the tests package. I tried every method but couldn't solve this problem while I tried to run valid_test.py
You need to use one dot before the functions so the python will know it is in the folder "above" the current location (import statement).
This look like this issue.
When specifying what module to import you do not have to specify the
absolute name of the module. When a module or package is contained
within another package it is possible to make a relative import within
the same top package without having to mention the package name. By
using leading dots in the specified module or package after from you
can specify how high to traverse up the current package hierarchy
without specifying exact names. One leading dot means the current
package where the module making the import exists. Two dots means up
one package level. Three dots is up two levels, etc. So if you execute
from . import mod from a module in the pkg package then you will end
up importing pkg.mod. If you execute from ..subpkg2 import mod from
within pkg.subpkg1 you will import pkg.subpkg2.mod. The specification
for relative imports is contained within PEP 328.
There is another way to solve this issue by adding the "father" folder to the sys.path
by:
import os
import sys
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__, '..')))
I have been getting the same problem again and again while using SPYDER with anaconda.
I make my own function in other file and import those functions. The code was still not running giving me the error "ModuleNotFoundError: No module named 'my_functions".
I am sure you are selecting lines and executing only selected line only\
Solution to problem is here below
To execute your code as whole/line by line Follow the steps.
Change the working directory of spyder to the folder of current file as here https://pasteboard.co/ee79y0dLqzu4.png .
select lines and execute or you can also execute the whole code.

Import statement breaks in class-containing module when importing the class from different files

Here's my directory structure:
app
-Folder1
-class-container.py
-queries.py
-script.py
-Folder2
-Folder3
-main.py
In my class-container file I import the SQL queries from queries.py with from Folder1.queries import sql_queries
When I import and use the class in main.py everything runs smoothly. But when I do the same from script.py I get a ModuleNotFoundError... no module named Folder1. I've tried relative imports and changing it to from queries import sql_queries but every time I change it, it breaks one or the other. Any insight would be valuable. Thanks!

Importing node modules once for whole project

Scenario
So, I have initialised a Node project with npm. I have setup my package.json accordingly. I am using typescript, so I have also setup tsconfig.json.
I have a few dependencies (npm packages) that I will need to use multiple times in multiple files of my project.
index.ts is the root of my project. I can import these libraries in index.js and other files also.
Problem
Is there any way to include or import these libraries in the project only once so that I can use them in any file of the project without having to import a single thing anywhere.
I tried searching for various ways to do this using -
CommonJS module syntax, NodeJS module syntax, global modules - but none of it can provide me the way I want it.
For Ex -
Most of the answers or solutions I got were like this
Export all the libraries through a single file
import abc from 'abc';
import xyz from 'xyz';
module.exports = {
abc, xyz
};
Use these libraries in other files like
import modules from 'src/modules.ts'
var wantSome = modules.abc.getSome();
But, this still has an overhead of importing modules file and accessing it like modules.abc.
Do we have any way to make these imports available globally through out the project.
P.S. - This scenario is somewhat similar to ngModules in Angular 2+, where we can import whatever we want inside ngModules and it is then available to all the components under that module.
Doing this is going to cause you all sorts of problems in the long run.
you'll end up with one monolithic file containing all your exports, which will become onerous to maintain
if you decide to modularise your code, it will be more difficult since you won't explicitly know which modules a file uses
if you were able to include to the point where you simply use the modules with no reference, code clarity will suffer
name clashes might occur
The best I believe you'll get in node is to declare all the includes in a single module, and then destructure within your own file.
import abc from 'abc';
import xyz from 'xyz';
module.exports = {
abc, xyz
};
Then
import modules from 'src/modules.ts'
{ abc: { getSome } } = modules
But I strongly suggest using the standard patterns for importing. It will make your code much cleaner and easier to maintain
N/B - Thats a bad way to design your app.
In node, you can set global variables via the "global" or "GLOBAL" object:
You could import all your dependencies in your app entry file, and store them in a Global variable
index.js
import abc from 'abc';
import xyz from 'xyz';
global.abc = abc
global.xyz = xyz
someotherfile.js
//access abc import
global.abc
Export all the libraries through a single file
import abc from 'abc';
import xyz from 'xyz';
module.exports = {
abc, xyz
};
Use these libraries in other files like
import {abc, xyz} from 'src/modules.ts'
var wantSome = abc.getSome();

Resources