I have encode\decode up (React Next.sjs + Node.js Express). I've done almost everything I wanted. The only one problem I don't know how to solve this is decoding. For decoding\encoding I'm using Cryptr library.
Here below my decode function code:
export const decodeBlog = async(req, res, next) => {
const { text, secretkeyword } = req.body;
const cryptr = new Cryptr(secretkeyword);
const encrypted = text;
let decrypted; //The problem is here
try {
const decrypted = cryptr.decrypt(encrypted, secretkeyword);
console.log("encrypted data", decrypted);
} catch (err) {
console.log(err);
return res.status(400).json({message: "Incorrect Secret keyword"});
}
return res.status(200).json({message: decrypted});
};
Here in postman I'm getting an empty {} brackets.
But in node.js console I have console.log and it works:
I will be really appreciate if you help me. Thank you in advance!:)
You have two variables named decrypted:
one inside the try-catch block: this one is declared with const, it gets a value and is output with console.log
one outside the try-catch block: this one is declared with let and output with res.json, but it never gets a value.
Omit the word const inside the try-catch block. The let outside suffices.
Related
In my express code I have a config in json, refer to the "template" variable below. I am doing some modifications in it for some purpose in call one and then in my second call when I am trying to get it, it is returning the modified value of field xyz that is A while I expect it to return the original config.
I did try to move that first line "const template = xxx" inside each method so that a new object gets created but it is still having the same issue. How can I fix this?
const express = require("express");
const { db, pgp } = require("../../helpers/dbConnection");
const { auth } = require("../middlewares/Auth");
const router = express.Router();
const template = require('../../config/template.json');
router.get("/callone", async (req, res) => {
try {
template.xyz = "A"
return res.status(200).send();
}
catch (err) {
return res.status(500).send(err.message);
}
});
router.get("/calltwo", async (req, res) => {
try {
return res.status(200).send(template);
}
catch (err) {
return res.status(500).send(err.message);
}
});
This approach is generally a bad idea.
It doesn't work if you ever want to scale beyond 1 server.
It doesn't work when there's more than 1 user using the system at the same time.
The right way to handle something like this is by adding either a database, or a session system.
Sessions feels like the right approach here, because that concept is specific for letting you store information specific to a user, and store/retrieve that over the course of several requests.
I am using AWS Comprehend's "PII" detection tools to spot personally identifying information (PII) in arbitrary text submitted by the public.
This is for a Nodejs Lambda that I mean to run in our AWS account.
const {Comprehend} = require('#aws-sdk/client-comprehend');
const client = new Comprehend({ region: "us-east-2" });
module.exports.handler = async (event, _context) => {
const message = event.data;
var redactedMessage = await getRedactedMessage(message);
return redactedMessage;
}
const getRedactedMessage = async (message) => {
// the Comprehend PII system takes strings up to 4000 characters
// so we split it on word boundaries after 4000 chars or less.
var messageParts = message.match(/.{1,4000}(\s|$)/g);
var redactedString = "";
for (const part in messageParts) {
try {
const checkPart = {
Text : message,
LanguageCode : "en"
};
client.detectPiiEntities(checkPart, function (err, pii) {
console.log("Why does this come last?");
});
} catch (error) {
console.error(error);
} finally {
console.log("Why do I get here first?");
}
console.log("And here? Then suddenly...");
}
}
No matter what, the output is
Why do I get here first?
And here? Then suddenly...
Why does this come last?
I have littered this with every possible combination of "async" and "await" commands. I have rewritten the client.detectPiiEntities(checkPart, function (err, pii)... line like a promise with a .then() but no matter what, I can't make it wait for the results of client.detectPiiEntities block.
I'm sure it's something dumb. (Probably me.) Thanks in advance.
I have a function that needs to read from a file, then convert it to an json object with JSON.parse(string) and lastly return it to be used elsewhere.
this object is written to a txt file using JSON.stringify():
let User = {
Username:"#",
Password:"#",
FilePaths:[
{Year:'#', Month:'#', FileName:'#'}
]
}
the writing works fine, my problem is the reading,
Here is my code:
const readFileAsync = promisify(fs.readFile);
async function GetUserData(User) {
const Read = async () => {
return await (await readFileAsync('UserData\\'+User.Username+'\\UserData.txt')).toString();
}
return Read().then(data=>{return JSON.parse(data)})
}
console.log(GetUserData(User));
The result I get back is :
Promise {[[PromiseState]]: 'pending', [[PromiseResult]]: undefined}
How can I make this work so
In this instance, GetUserData returns a promise, so you'll need to use .then to get the data once resolved.
GetUserData(User).then(data => {
// do something with data
});
Alternatively, fs has a sync function you can use, rather relying on readFile (which is async), use readFileSync. Usage below:
function GetUserData(User) {
const data = fs.readFileSync('UserData\\'+User.Username+'\\UserData.txt').toString();
return JSON.parse(data);
}
console.log(GetUserData(User));
I have the function, enter, that contains two fs.readFile functions inside and on the innermost readfile I'm checking to see whether a txt file contains a certain keyword, and if it does it should stop the entire enter function.
Her is what the enter function looks like:
async function enter(email, firstName, lastName){
fs.readFile(fileName, function(err, data){
parsedData = JSON.parse(data);
email = parsedData.email;
fs.readFile('./anotherfile.txt', function (err, data) {
if (err) throw err;
if(data.includes(email)){
console.log('Stopping function');
return;
}
});
});
console.log('Continuing with function');
}
The problem is that when anotherfile.txt contains the keyword, it does not stop the entire function, it continues and logs, "Continuing with function" as seen in the code above.
Any help would be appreciated!
fs promises are available Node v11.0.0
or You can can convert like this const readFile = util.promisify(fs.readFile);
const fsp = require('fs').promises;
async function enter(email, firstName, lastName) {
try {
let data = await fsp.readFile(fileName)
let parsedData = JSON.parse(data);
let email = parsedData.email;
data = await fsp.readFile('./anotherfile.txt')
if (data.includes(email)) {
console.log('Stopping function');
return;
}
console.log('Continuing with function');
} catch (err) {
throw err
}
}
This is because of two things.
You are using asynchronous File read, that is, the flow of code won't stop when this readFile is called. Instead, the program would keep executing in a normal fashion. And when the file read operation is completed, the callback function you supplied will be called with the corresponding error or data.
The return statement is inside of the callback function, hence it will only affect that function.
You need to use await when you are dealing with asynchronous functions. Look that up here
I'm writing a RESTful API in typescript and I'm trying to use my already parsed data that is stored in redis with a specific key in another function. The problem I am having is that instead of receiving the actual data from redis, I just keep receiving a boolean value of true. I have tried googling a lot and reading the redis documentation, unfortunately to no avail. Does anyone here now how I can access the actual data so I can use it in another function? I suspect I am facing some kind of async problems here, but I am not entirely sure.
For example if I try to bind the response to a variable this will happen:
const key = something
const reply = client.mget(key);
console.log("This is the reply: " + reply);
This is the reply: true
Br,
Victor
EDIT:
So basically I'm sending the data from https.get into an object handler, which parses the data into my preferred form and then I stringify that object and send it into redis as a string, which looks like this:
client.set(redisInfo, JSON.stringify(objecthandler(newdata)));
My actual code for getting the data at the moment looks like this:
const getRedis = (rediskey: string, success: any, error: any) => {
client.mget(rediskey, function (err: Error, reply: any) {
if (!err) {
success(reply);
}
else {
error(err);
}
});
};
//My callback function that I'm trying to get to work so I can use the redis data in other functions
function getrediscallback(key: string) {
getRedis(key, function success(reply: string): string {
//This console.log actually returns the data that I want
console.log("this is the reply: " + reply);
return reply;
},
function error(err: Error) {
console.log("Something went wrong" + err);
});
}
So when I use the callback in another function, it will look something like this:
const redisdata = getrediscallback("getCars");
//This gives me the value of undefined
console.log(redisdata)
This means that the callback function actually gets the actual data, but it is never reached later on when I use the callback function in another function.
const redis = require('redis');
const client = redis.createClient(6379);
const bluebird = require("bluebird");
bluebird.promisifyAll(redis.RedisClient.prototype);
bluebird.promisifyAll(redis.Multi.prototype);
const redisdata = await client.getAsync('user:photos');
if (redisdata) {
console.log(`cache EXISTS`)
return res.json({ source: 'cache', data: JSON.parse(redisdata) })
}
import util from "util";
import redisClient from "../config/redisConfig";
let hgetall = util.promisify(redisClient.hgetall).bind(redisClient);
await hgetall("Key")