What is a UnhandledPromiseRejectionWarning: ReferenceError in Node Javascript? - javascript

I had working express Node Javascript code, but when I changed the code to give me a random id for each file input (instead of a set file name, myFile.jpeg), I get the following error:
UnhandledPromiseRejectionWarning: ReferenceError: fileName is not defined
I know that I've defined the fileName, but I don't understand what this error means or how to fix it. I've seen this error a lot of Discord bots or MongoDB, but I'm having a hard time finding anything for express.
let rid = Math.floor(Math.random() * 10000000)
let ridString = "" + rid
//const upload = multer().single('myfile')
const upload = multer().single(ridString)
//other code
app.post('/upload', (req, res)=>{
upload(req, res, async function(err){
if( err|| req.file === undefined){
console.log(err)
res.send("error occured")
}else{
//let rid = Math.floor(Math.random() * 10000000)
//let ridString = "" + rid
let fileName = ridString + ".jpeg"
//let fileName = "myfile.jpeg"
var image = await sharp(req.file.buffer)
//.catch(err => {console.log('error: ', err)})
.jpeg({
//quality: 40,
}).toFile('./uploads/'+fileName)
.catch( err => { console.log('error: ', err) })
pythonFunction(res, fileName);
}
})
})
I've commented out everything that got changed from myFile to the random number.

Related

Javascript Discord Bot Error (Function Error)

I always get an error message after adding the reload command.
Without the Reload Command, the bot works with all commands without any problems
Without the Reload Command, the bot works with all commands without any problems
I just can't find the mistake
The error message:
undefined commands found.
/home/runner/Discord-BreakpointBot/index.js:19
delete require.cache[require.resolve(`./commands/${f}`)];
^
TypeError: require.resolve is not a function
Code:
function loadCmds () {
fs.readdir('./commands/', (err, files) => {
if(err) console.error(err);
var jsfiles = files.filter(f => f.split('.').pop() === 'js');
if (jsfiles.length <=0) {return console.log('No commands found...')}
else {console.log(jsfiles.lenght + ' commands found.')}
jsfiles.forEach((f,i) => {
delete require.cache[require.resolve(`./commands/${f}`)];
var cmds = require(`./commands/${f}`);
console.log(`Command ${f} loading...`);
bot.commands.set(cmds.config.command, cmds);
})
})
}
bot.on('message', message => {
var sender = message.author;
var msg = message.content.toUpperCase();
var prefix ='>'
var cont = message.content.slice(prefix.length).split(" ");
var args = cont.slice(1);
if (!message.content.startsWith(prefix)) return;
var cmd = bot.commands.get(cont[0])
if (cmd) cmd.run(bot, message, args);
if (msg === prefix + 'RELOAD') {
message.channel.send({embed:{description:"All Commands Reloaded"}})
message.channel.send('All Commands Reloaded')
loadCmds()
}
});
loadCmds();
// Bot Launched
bot.on('ready', () => {
console.log('Bot Launched...')
bot.user.setStatus('Online')
bot.user.setActivity('https://www.twitch.tv');
});
I hope someone can help, thanks
I'm not 100% sure what causes your error but I can offer you my method of retrieving comamnds, which works pretty well:
const fileArray = [];
function readCommands(dir) {
const __dirname = rootDir;
// Read out all command files
const files = fs.readdirSync(path.join(__dirname, dir));
// Loop through all the files in ./commands
for (const file of files) {
// Get the status of 'file' (is it a file or directory?)
const stat = fs.lstatSync(path.join(__dirname, dir, file));
// If the 'file' is a directory, call the 'readCommands' function
// again with the path of the subdirectory
if (stat.isDirectory()) {
readCommands(path.join(dir, file));
}
else {
const fileDir = dir.replace('\\', '/');
fileArray.push(fileDir + '/' + file);
// fs.readdirSync(dir).filter(cmdFile => cmdFile.endsWith('.js'));
}
}
}
readCommands('commands');
for(const file of fileArray) {
const command = require(`../${file}`);
if(command.name) {
client.commands.set(command.name, command);
}
else {
continue;
}
}
This will recursively search the folder you specify when calling the function and then store it in fileArray.
This solution is more an alternative than an exact solution to the error you are experiencing

Why is dns.lookup working on these incorrect URLs?

I'm currently trying to create a URL shortening microservice with Node.js. I'm passing in incorrect strings to dns.lookup() to check if they are valid URL's, however instead of returning an error, they are returning an address and a family.
dns.lookup('hello', (err, address, family) => {
if(err) {
res.send('invalid')
return
} else {
console.log(`error = ${err}`)
console.log(`address = ${address}`)
console.log(`family = ${family}`)
next()
}
});
Console:
error = null
address = 92.242.132.24
family = 4
I'd like it to pass an error if the URL is invalid.
EDIT: Adding full code if that helps?
var express = require('express')
var app = express()
var cors = require('cors')
var dns = require('dns')
dns.lookup('hello', (err, address, family) => {
if(err) {
console.log(`error = ${err}`)
//res.send('invalid')
//return
} else {
console.log(`error = ${err}`)
console.log(`address = ${address}`)
console.log(`family = ${family}`)
//next()
}
});
var listener = app.listen(3001, function(){
console.log('working on port 3001')
});
It turns out my ISP (Virgin Media) has a third party called Barefruit Ltd that intercepts dns errors and sends back advertising instead: https://www.barefruit.com/
For the meantime, I've found a workaround by adding if(err || address == '92.242.132.24') to my error handling.

Not able to load image from local node js server in face-api.js

i tried the following two ways o fetch image from localserver in node js in face-api.js a and output of the following codes are commemnted
should i missing something or i need to try different way please help..
1st try
var image = fs.readFileSync(path);
console.log('Exists ' + typeof (image)) // Exists object
const image = await faceapi.fetchImage(image)
.then(res =>{console.log(res)})
.catch(e=> console.log("Error e "+e)) //Error e Type Error: Only absolute URLs are supported
i wanted to fetch images from loccal server and train the model but i'm not able to fetch the image. the full error is below:-
(node:25194) UnhandledPromiseRejectionWarning: TypeError: Only absolute URLs are supported
at getNodeRequestOptions (/home/milind/Desktop/FaceApi/Face-Detection-JavaScript/node_modules/node-fetch/lib/index.js:1299:9)
at /home/milind/Desktop/FaceApi/Face-Detection-JavaScript/node_modules/node-fetch/lib/index.js:1404:19
at new Promise (<anonymous>)
at fetch (/home/milind/Desktop/FaceApi/Face-Detection-JavaScript/node_modules/node-fetch/lib/index.js:1401:9)
at Object.<anonymous> (/home/milind/Desktop/FaceApi/Face-Detection-JavaScript/node_modules/tfjs-image-recognition-base/build/commonjs/dom/fetchOrThrow.js:12:42)
at step (/home/milind/Desktop/FaceApi/Face-Detection-JavaScript/node_modules/tslib/tslib.js:136:27)
at Object.next (/home/milind/Desktop/FaceApi/Face-Detection-JavaScript/node_modules/tslib/tslib.js:117:57)
at /home/milind/Desktop/FaceApi/Face-Detection-JavaScript/node_modules/tslib/tslib.js:110:75
at new Promise (<anonymous>)
at Object.__awaiter (/home/milind/Desktop/FaceApi/Face-Detection-JavaScript/node_modules/tslib/tslib.js:106:16)
ps i already checked this
face-api.js load image file from disk
Edit:
Repository
-temp
image.png
server.js
-Router
router.js <- here i'm having the below router code
router.post('/upload-file-face', (req, res) => {
console.log("Helllo");
Promise.all([
faceapi.nets.faceRecognitionNet.loadFromDisk('./weights'),
faceapi.nets.faceLandmark68Net.loadFromDisk('./weights'),
faceapi.nets.ssdMobilenetv1.loadFromDisk('./weights'),
]).then(async () => {
tempUpload(req,res, async(err) =>{
console.log(req.files);
if(err) {
return res.end("Error uploading file." + err);
}
var location = "./"+req.files[0].destination
var imgFile = req.files[0].filename;
if(!fs.existsSync(fspath.join(location,imgFile))) {
console.log("Not exists")
}else{
console.log('Exists') //yes Exists
}
var pp =fspath.join(location,imgFile);
console.log("path : "+pp)
const image = faceapi.fetchImage(pp)
.then(res =>{console.log(res)})
.catch(e=> console.log("Error e " +e)) // Error e TypeError: Only absolute URLs are supported
res.send("hello");
})
})
})
According to the docs the faceapi.fetchImage accepts an path, not filecontent/buffer.
So, instead of doing var image = fs.readFileSync(path) you should just do:
try{
const image = await faceapi.fetchImage(path)
} catch (e){
console.log("Error e "+e)
}
fetchImage will not work with a local resource, because "fetch" is for the web.
You'll want to npm install canvas and then simply do this:
const canvas = require('canvas');
faceapi.env.monkeyPatch({ Canvas, Image })
const img = await canvas.loadImage('./img.jpg');
const detections = await faceapi.detectSingleFace(img);
See another discussion: https://stackoverflow.com/a/59828665/5017391

fs.readdir and fs.readfile and regex

This is a Node application, running express server. I have a folder with text files in it. I need to be able to go into each one of those files inside the folder, and extract lines that include a word "SAVE".
I am stuck at this step.
app.get('/logJson', function (req, res) {
const logsFolder = 'C:/logs/';
fs.readdir(logsFolder, (err, files) => {
if (err) {
res.send("[empty]");
return;
}
files.forEach(function(filename){
var logFiles = fs.readFileSync (logsFolder + filename, 'ascii').toString().split("\n");
console.log(logFiles + "\n");
})
})
})
I cannot figure out where do I include this:
var log = (logFiles.split(/.*SAVE.*/g)||['no result found'])[0];
Any help would be appreciated
If you only want to print out all lines containing the word SAVE, you could do it like this.
Remark: I did not run this code.
app.get('/logJson', function (req, res) {
const logsFolder = 'C:/logs/';
fs.readdir(logsFolder, (err, files) => {
if (err) {
res.send("[empty]");
return;
}
var lines = [];
files.forEach(function(filename) {
var logFileLines = fs.readFileSync (logsFolder + filename, 'ascii').toString().split("\n");
// go through the list of logFileLines
logFileLines.forEach(function(logFileLine) {
// if the current line matches SAVE, it will be stored in the variable lines
if(logFileLine.match(/SAVE/)) {
lines.push(logFileLine);
}
})
})
// the variable lines is printed to the console
console.log(lines);
})
})

Error with NodeJS FS (writeFile)

Here is my piece of my router who manage my uploads :
fs.readFile(files.photo.path, function (err, data) {
// Here is the futur name of my file (ex: SERVER_PATH/images/moka/moka22/11/2016_1.jpg)
var newPath = __dirname + "/images/moka/moka" + new Date().toLocaleDateString() + "_" + Math.floor(Math.random() * 10) + 1 + "." + ext;
fs.writeFile(newPath, data, function (err) {
if(err) {
res.render('error', { error: err, message: "Erreur lors de l'upload"});
} else {
// insctructions
});
}
});
});
When the code is triggered I have this error :
Error: ENOENT: no such file or directory, open 'D:\projects\raspberry\routes\images\moka\moka2016-11-22_91.jpg'
at Error (native)
If I well understood the fs doc (https://nodejs.org/api/fs.html#fs_fs_writefile_file_data_options_callback) :
fs.writeFile(theNameOfTheFuturFile, theDataToPutIn, callback);
So I'm a bit confused.
Sorry for my english, it may be bad, i hope that you guess what i mean :)
Thanks.
The problem could be the directory you are writing to does not exist.
so make sure it exists:
fs.readFile(files.photo.path, function (err, data) {
var dirPath = __dirname + "/images/moka/moka";
if (!fs.existsSync(dirPath)){
fs.mkdirSync(dirPath);
}
...
or do it by hand.

Categories