send data from file to file in express - node.js

so what I want to do is sending an string which is a path for my image .. I want to do that in routes file . because I receive in it the image path like that
const imageReko = require("./image-Reko");
if(req.body.act === "post") {
if(req.body.img){
imageReko(req.body.img)
}
const post = new Post({
content: req.body.content,
firstName:req.body.firstName,
lastName: req.body.lastName,
img: req.body.img,
});
so what I have done is export all my image recognition file like that
const imageReko = () =>{
const photo = 'image2.jpg' // i want to put my string that i have passed it from my route files
// somecode
}
I described in comment what I want to do ..

From what I understand you want to get a string from the request body then pass it into a function in ./image-Reko which will store it in a variable.
Function Parameters
First of all the function in `image-Reko` has no parameters. This means when you pass `req.body.img` the function will ignore it since it cannot use it. To fix this you need to add a parameter to the function like so:
const imageRecko = (img) => {
// Code here
}
const vs. var and let
In the function you defined a variable called `photo` with the keyword `const` which declares a constant variable. This variable can not be re declared or redefined so you can change this variable with your function. To fix this:
const imageReko = (img) => {
var photo = img;
}
This way you can assign the variable inside the function.
This is what i understood from your question let me know if i missed something. Good luck with your project!

Since you pass req.body.img as parameter for imageReko() you can use it in the imageReko function
const imageReko = (img) =>{
const photo = img
// somecode
}

Related

How to break a single node.js file into many?

Hi,
I have an app on node.js which consists of a single file app.js that looks like this:
//variables
app = require("express")();
//many more variables here
//functions
function dosomething {}
//many more functions here
but since its getting a little too long I would like to break it into several files, one for variables only (variables.js) and another one for functions only (functions.js) and load them from app.js like this like when you do it with php
//variables
include(variables.js);
//functions
include(functions.js);
is it even possible to do that? Or I have to include everything in one single file like I do now?
Thank you.
You can use Module.Export to export a separate file, and import it into another file using the require statement. Please check here for details:
https://www.geeksforgeeks.org/import-and-export-in-node-js/
Happy Learning :-)
Importing API Endpoints
You can do this by using app.use(...) and point each endpoint to a specific file like so:
const express = require("express");
const app = express();
// User Functions
app.use("/api/user", require("./routes/api/user"));
//Orders functions
app.use("/api/orders/", require("./routes/api/orders"));
/**
* Express Server Init
*/
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server started on ${PORT}`));
Then in /routes/api/user/user.js you would have something like:
const express = require("express");
const router = express.Router();
router.post("/create", (req, res) => {
try {
// Create user
} catch (error) {
console.log(error);
res.sendStatus(500);
}
});
module.exports = router;
Add and index.js inside /routes/api/user to point at the user file to keep things pretty when importing (otherwise you have to import it like /routes/api/user/user):
const user = require("./user");
module.exports = user;
Importing Single File
Not sure your use case but variables could be a bad naming convention since these values are more like constants than variables. Either way, you create it like this:
const variables = {
varibleOne: "valueOne",
varibleTwo: "valueTwo",
varibleThree: "valueThree",
};
module.exports = variables;
Then wherever you want to import it you can do:
const variables = require("./variables");
and access it like so variables.variableOneand so on.
Importing functions
You can also import different functions, say you need a file called helper.js where these are commonly functions needed all over you app, you could do something like this:
const twoDecimals = (number, decimal = ",") => {
let val = (Math.round(number * 100) / 100).toFixed(2);
return decimal === "." ? val : val.replace(".", decimal);
};
const getRandomInt = (max) => {
return Math.floor(Math.random() * Math.floor(max));
};
module.exports = { twoDecimals, getRandomInt };
Then wherever you needed you can import it by:
const { twoDecimals } = require("helper.js");
Now you have access to your helper functions anywhere.
You should get help from the JavaScript modular system (preferably COMMONJS).
For example, suppose we have two files:
1-module.js 2-app.js
So now let's create this files
module.js
let name = "hello world";
function printSomething(message) {
console.log(message)
}
//here export all function and variable
module.exports.name = name;
module.exports.printSomething = printSomething
ok so Well now it is enough that "require" this file in main file :
main.js
// we
const {name, printSomething} = require("./module.js");
printSomething(name);
for export all variable You need to create an object and specify your variables as a property:
let host = "localhost"
let dbname = "laravel_8"
let username = "root"
let password = "root"
function doSomething() {
console.log("hello");
}
module.exports = {host, dbname, username, password, doSomething}
so in main file :
const variables = require("./module.js")
//host
let host = variables.host
//dbname
let dbname = variables.dbname
//function doSomething
let doSomething = variables.doSomething;
doSomething()
// or directly
variables.doSomething()
In fact, in php we use the "->" symbol to access properties, and in JavaScript we use "."

Is it possible to module.exports a local variable from async function?

I have this async function in a file called index.main.js which has a variable , 'targetFiles' which I would like to export to another file which is index.js. Problem is I can't find a way to export the value of this particular variable without getting "undefined" as a result.
I have tried implementing promise, callback , export default function, and doing countless hours of research to no avail.
//this code is in index.main.js
var targetFiles = "";
async function listFilesInDepth()
{
const {Storage} = require('#google-cloud/storage');
const storage = new Storage();
const bucketName = 'probizmy';
const [files] = await storage.bucket(bucketName).getFiles();
console.log('List Of Files Available:');
files.forEach(file =>
{
targetFiles = file.name; //this is the variable to export
console.log(`-----`+file.name);
});
return targetFiles;
}
module.exports = {
fn : targetFiles
}
trying to export the value to index.js is either empty or "undefined"
//this is the code in index.js
const a = require('./index.main');
console.log(a.fn); //undefined or empty
The expected value that should be the output is the value of targetFiles. Let's say if targetFiles is abc12345.JSON in the async function,the console.log in index.js should be of that value.
I'm hoping someone could give me some insight on how I could overcome this issue. Thank you in advance :)
Following solution might help you, but not sure for your use case. (Not using module-exports):
You can use request-context package to achieve same functionality.
What is package does is, you can set the value(data) against a key and then access the same in the following code execution within the same context.
Run npm install request-context
In your main app.js (server file), register the request-context as a middleware.
const contextService = require("request-context");
const app = express();
...
// Multiple contexts are supported, but below we are setting for per request.
app.use(contextService.middleware("request"));
...
And then in your index.main.js, once targetFiles is ready, set the targetFiles into request context.
const contextService = require("request-context");
...
files.forEach(file =>
{
targetFiles = file.name; //this is the variable to export
console.log(`-----`+file.name);
});
// Here `Request` is the namespace(context), targetFileKey is the key and targetFiles is the value.
contextService.set("request:targetFileKey", targetFiles);
return targetFiles;
}
...
And in the same request, where you wanna use targetFile, you can do the following:
index.js (Can be any file where you need targetFiles after being set):
const contextService = require("request-context");
...
// Reading from same namespace request to which we had set earlier
const targetFiles = contextService.get("request:targetFileKey");
...
Please note:
You will be able to access targetFiles in the same request you set. That means, request-context we configured in app.js is per API request, meaning, in every API request, you have to set it before reading.
Please let me know if the above solution doesn't fit for you.

Is there a way to change the mocked value of a required dependency?

I'm facing a problem I'm not able to resolve on my own, maybe some of you faced the same problem.
Let me show you what I'm trying to do, here is the mock:
let mockConfig = {name: 'dude'};
jest.mock('../../../configManager', () => mockConfig);
configManager is a dependency of the function I'm trying to test.
It works well but I want to change the returning object of configManager in another test so the tested function behaves differently.
Let me show you, here is the function I'm testing:
const config = require('../../../configManager');
module.exports = () => {
if (config.name === 'dude') {
do stuff;
}
if (config.name === 'dudette') {
do something else;
}
So, typically, I want to change the config.name to 'dudette' to be able to test the second part of my function.
Naturally, when I want to do this with an imported function, I just do:
let mockJsonQueryResult = { value: 'stuff' };
jest.mock('json-query', () => jest.fn(() => mockJsonQueryResult));
and then in the test, I directly set another value to mockJsonQueryResult:
mockJsonQueryResult = { value: 'hotterStuff' };
But I don't find any way of doing this with a dependency that returns an object, with a dependency returning a function, no problem.
Is there even any way of doing this?
Thanks in advance!
Edit: this is not the same as how to change jest mock function return value in each test? as #Dor Shinar suggested because his problem is to mock a function, even if it is inside a returning object it is still a function, I just want to change a value inside the returned object.
So, I found a solution I'm not completely satisfied with but it works:
I simply set the original full object and then for my tests, change the value of specific properties by setting them directly before calling the function I want to test.
example:
let mockConfig = { person: { name: 'dude', origin: {country: 'France'} } };
jest.mock('../../../configManager', () => mockConfig);
mockConfig.person = {};
mockConfig.person.name = 'dudette';
You don't need to mock the module at all.
If your module export is just an object with property values then just change the properties as needed.
Here is a simple working example to demonstrate:
configManager.js
module.exports = {
name: 'original'
}
code.js
const config = require('./configManager');
module.exports = () => `name: ${config.name}`;
code.test.js
const config = require('./configManager');
const func = require('./code');
test('func', () => {
expect(func()).toBe('name: original'); // Success!
config.name = 'dude';
expect(func()).toBe('name: dude'); // Success!
config.name = 'dudette';
expect(func()).toBe('name: dudette'); // Success!
})
Details
A module binding can't be directly changed to something else:
const config = require('./configManager');
config = { name: 'mock' }; // <= this doesn't work
...but you can change the properties of an object representing a module binding:
const config = require('./configManager');
config.name = 'mock'; // <= this works!
...and any code using the module will automatically see the changes.

Move arrow function to another exported function

I have a problem. I want to clean my code and put function to another file but I always get an error:
getMe is not a function
why? I want to use it in already exported function getExchangeRateIntent. Is that causing a problem?
outside.js
const getRate = (base) => {
console.log('My base currency is '+base);
};
module.exports = {getRate};
getRate.js
const getMe = ('./outside.js');
module.exports = {
'getExchangeRateIntent': (conv, parameter) => {
const currencyBase = (parameter['currencyBase']);
const currencyTarget = (parameter['currencyTarget']);
const amount = (parameter['amount']);
console.log(currencyBase);
console.log(currencyTarget);
console.log(amount);
getMe('USD');
conv.ask('nothing');
},
};
module.exports = {getRate}; you are exporting an object. With your import:
const getMe = ('./outside.js');
you are importing an object. So this is not a function. This is not a proper import also.
For proper import you could write something like this:
import {getRate} from './outside.js;
And use it like this:
getRate('USD');
Or if you want to use require:
const getMe = require('./outside.js');
And then you can call function like this in second case:
getMe.getRate('USD')

Node convert variable value to variable name for use in destructuring assignment

I have a models folder with an index.js file that looks like the following:
'use strict';
const {Dest1} = require('./destinations/dest1');
const {Dest2} = require('./destinations/dest2');
module.exports = {Dest1, Dest2};
I would like to dynamically load these objects based on a condition. I was thinking it might be interesting to have a middleware function that appends a value to the request that I could use to look up the correct object. I could just dynamically load the path, but I'm curious if this is possible.
Middleware:
function checkDestination(req,res,next){
if('destination1' in req.body){
req.path = 'Dest1'
}
next()
}
Router:
router.get('/', checkDestination, (req,res)=>{
//convert req.path to variable name here
const {Dest1} = require('./models')
})
Symbols?
Ok, decided to go with a hashtable or dictionary look up to avoid repeating a bunch of if statements. If the above is possible, it would be less code but this is pretty clean too.
Middleware:
function checkDestination(req,res,next){
if('destination1' in req.body){
req.destination = 'destination1'
}
next()
}
HashTable:
const {Dest1} = require('../models')
const destLookUp = {
destination1:function(destObj){
return Dest1.create({})
.then(newDest=>return newDest})
.catch(error=>{console.log(error)})
}
}
module.exports = {destLookUp}
Router:
destLookUp[req.destination](destObj)

Resources