Unzipper stream "Bad password" issue in node js - node.js

I am extracting password protected zip in node js for this i am using unzipper node module. below is the code which i am using.
const unzipper = require('unzipper');
const fs = require('fs');
const path = require('path');
async function checkPasswordValid(zipFilePath, password) {
let directory = null;
try {
directory = await unzipper.Open.file(zipFilePath);
return new Promise((resolve, reject) => {
// console.log(directory.files[0].path)
directory.files[0].stream(password)
.on('error', (err) => {
console.log('I am heere too bro in error')
console.log(err.message);
})
.on("readable", () => {
console.log('I am heere too bro')
})
});
}
catch (err) {
console.log('I am heere too bro in error in catch')
console.log(err.message);
}
}
let zpath = 'D:/NodeJs/upload/zip/text.zip';
let exPath = 'D:/NodeJs/upload/extractFile/';
let pass = 'DEXTER';
checkPasswordValid(zpath, pass)
when i try to manually open zip with password it's works fine but when i am using same password with node module unzipper i am getting below error.
I am heere too bro in error
BAD_PASSWORD
(node:6100) UnhandledPromiseRejectionWarning: #<Object>
(node:6100) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:6100) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
I don't know where i am doing wrong. Code looks perfect for me but not working. to made password protected zip i used winrar software on windows 10.

It appears that unzipper doesn't support all encryption methods. This issue has produced a feature request that has not been developed yet.

Related

MongooseError: Query was already executed: User.countDocuments({})

(node:9540) UnhandledPromiseRejectionWarning: MongooseError: Query was already executed: User.countDocuments({})
at model.Query._wrappedThunk [as _countDocuments] (D:\Acadamic-LANGUAGE-PROJECTS\Angular-Projects\eShop-MEAN STACK\Back-End\node_modules\mongoose\lib\helpers\query\wrapThunk.js:21:19)
at D:\Acadamic-LANGUAGE-PROJECTS\Angular-Projects\eShop-MEAN STACK\Back-End\node_modules\kareem\index.js:370:33
at processTicksAndRejections (internal/process/task_queues.js:77:11)
(Use node --trace-warnings ... to show where the warning was created)
(node:9540) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node
process on unhandled promise rejection, use the CLI flag --unhandled-rejections=strict (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:9540) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
this is my Code......
router.get(`/get/count`, async (req, res) =>{
const userCount = await User.countDocuments((count) => count)
if(!userCount) {
res.status(500).json({success: false})
}
res.send({
userCount: userCount
});
})
It seems that you are using Mongoose. It seems you are mixing between async-await and callbacks.
Change await User.countDocuments((count) => count) to
await User.countDocuments()
This is because countDocuments() is called using its callback (which passes its result to the callback), while on the other hand, it is also asked to pass its result to the userCount variable using the await command.
This is exactly what this error message is trying to say: hey, you're sending the same query to the database twice ! While, since since v6 of Mongoose, you can only get run query once - ie, either by adding the cbk argument, or using async-await block. Read about it here: https://mongoosejs.com/docs/migrating_to_6.html#duplicate-query-execution
Now let's move ahead to fixing the problem:
I don't completely understand what you're trying to do this in line:
const userCount = await User.countDocuments((count) => count)
I think what you're trying to do is just get the document count. If so, simply drop 'count => count'.
router.get(`/get/count`, async (req, res) =>{
const userCount = await User.countDocuments();
if(!userCount) {
res.status(500).json({success: false})
}
res.send({
userCount: userCount
});
})
If you were to add a filter to the count (which is what the countDocuments gets - a filter; see API here), then you should use the key:value pair form, ie {count: count}.
router.get(`/get/count`, async (req, res) =>{
/* let count; etc. */
const userCount = await User.countDocuments({count: count});
if(!userCount) {
res.status(500).json({success: false})
}
res.send({
userCount: userCount
});
})
Of course you should use a proper try-catch block when using await, to be able to handle the error if thrown.
(Just encountered this problem myself and made some research into it.)
module.exports.getUserCount = async(req,res)=>{
const numberOfUser = await User.countDocuments()
res.send({numberOfUser : numberOfUser});
}

Try to cach UnhandledPromiseRejectionWarning discord.js

i'm trying to catch an discord.js error
This error pops up when internet is off, but i want some clean code instead this messy one...
How can i catch this?
I did really try everything..
code:
(node:11052) UnhandledPromiseRejectionWarning: Error: getaddrinfo ENOTFOUND disc
ordapp.com
at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:66:26)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:11052) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This
error originated either by throwing inside of an async function without a catch
block, or by rejecting a promise which was not handled with .catch(). To termin
ate the node process on unhandled promise rejection, use the CLI flag `--unhandl
ed-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejecti
ons_mode). (rejection id: 2)
(node:11052) [DEP0018] DeprecationWarning: Unhandled promise rejections are depr
ecated. In the future, promise rejections that are not handled will terminate th
e Node.js process with a non-zero exit code.
i did try this at the very top :
process.on('uncaughtException', function (err) {
//console.log('### BIG ONE (%s)', err);
console.log("555")
});
aswell this one :
client.on('error', error => {
if (error.code === 'ENOTFOUND') {
console.log(no internet!!)
}
});
I also did try this to see where its from, but nothing shows up its still the same
try {
var err = new Error("my error");
Error.stackTraceLimit = infinity;
throw err;
} catch(e) {
console.log("Error stack trace limit: ")
console.log(Error.stackTraceLimit);
}
Error stack trace limit:
10
(node:11008) UnhandledPromiseRejectionWarning: Error: getaddrinfo ENOTFOUND disc
ordapp.com
here is the code i use for now what gives the error.
i just want to catch the error in something like this: (No connection)
const Discord = require('discord.js')
const client = new Discord.Client({ autoReconnect: true });
const opn = require('opn')
const getJSON = require('get-json')
const request = require('request');
const config = require("./config/config.json");
const pushbullet = require("./config/pushbullet.json");
const addons = require("./config/addons.json");
const Registration = require("./config/Reg.json");
client.on('uncaughtException', function (err) {
//console.log('### BIG ONE (%s)', err);
console.log("555")
});
client.login(config.Settings[0].bot_secret_token);
I would try to wrap it with try/catch.
And maybe add the following code to understand better what is happening.
Error.stackTraceLimit = Infinity
Reference:
https://developer.mozilla.org/en-US/docs/Archive/Web/JavaScript/Microsoft_Extensions/Error.stackTraceLimit
Remember to remove it after the problem solved, this is not suitable for production use.
Well i solved it!!
I put this on top and its all solved.
process.on('unhandledRejection', error => {
if (error.code === "ENOTFOUND") { console.log ("No internet connection")}
if (error.code === "ECONNREFUSED") { console.log ("Connection refused")}
//console.log('Unhandled promise rejection:', error.code);
});

Unit Testing HTTP Post request with database access

Hi I'm currently trying to learn and implement some unit testing for my HTTP Requests. currently I have a SQlite db setup, and a simple post request. This is the test I have written so far:
"use strict";
process.env.NODE_ENV = 'test';
const chai = require('chai');
const chaiHttp = require('chai-http');
chai.use(chaiHttp);
const expect = chai.expect;
const app = require('../../../app');
chai.request('http://localhost:8080')
.put('/tempValue')
.send({sensorid: '1', sensorValue: '25.00', timeRecorded: '2020-04-12 12:30'})
.then(function (res) {
expect(res).to.have.status(200);
})
.catch(function (err) {
throw err;
});
I seem to be getting a error that it is unable to open the database file. Currently I am just connecting to the database in the app.js file, using const dbPath = "./database/database.db"; and const dbConnection = sqlite.open(dbPath, { Promise });
I also seem to get errors about incorrect use of .catch? This is the error log:
(node:13952) UnhandledPromiseRejectionWarning: Error: SQLITE_CANTOPEN: unable to open database file
(node:13952) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unha
ndled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:13952) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
(node:13952) UnhandledPromiseRejectionWarning: AssertionError: expected { Object (_events, _eventsCount, ...) } to have status code 200 but got 404
at D:\Uni Work\3rd Year\302CEM - Agile Development\Penguin Project\test\api\temperature\get.js:15:29
at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:13952) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unha
ndled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
Thanks for any help!
EDIT:
This is the particular post request I'm testing, it uses MQTT to check if the message being sent is to that topic structure, then inserts into the database.
app.ws.use(route.all('/tempValue', function (ctx){
client.on('message', async function(topic,message){
console.log(topic, message.toString());
if (topic === '302CEM/Penguin/Room1/Temperature'){
const SQL = "INSERT INTO sensorData (sensorid, sensorValue, timeRecorded) VALUES (?,?,?)";
try {
const temptostring = message.toString();
const db = await dbConnection;
await db.run(SQL, ["1",temptostring, moment().format('YYYY-MM-DD HH:mm')]);
ctx.websocket.send(temptostring);
} catch (err) {
console.log(err);
}
}
})
}));

proxyReq.setHeader can not set headers after they are sent

i am building a node.js proxy and i want to add a conditional header
proxy.on('proxyReq', (proxyReq, req, res) => {
const realIP = parseHttpHeader(req.headers['x-real-ip'])[0];
const path = parseHttpHeader(req.headers['x-original-uri'])[0];
pAny([
check_ip(realIP) ,
check_path(path) ,
check_geo(realIP)
]).then(result => {
console.log (result , "result " )
if (result) {
proxyReq.setHeader('namespace' , 'foo');
} else {
proxyReq.setHeader('namespace' , 'bar'); }
console.log('sending req ')
});
});
.
async function check_ip(realIP) {
try {
const result = await ipModel.findOne({ip: realIP}).exec()
console.log(realIP , result , "ip")
if (result) {
return true
} else {
return false
}
} catch (e) {
throw e;
}
}
and it works just fine till i use the methos check_ip then i get the error
(node:3793) UnhandledPromiseRejectionWarning: Error: Can't set headers after they are sent.
at validateHeader (_http_outgoing.js:491:11)
at ClientRequest.setHeader (_http_outgoing.js:498:3)
at /home/master/IPS/server.js:109:14
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:189:7)
(node:3793) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:3793) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
as the error clearly states i am handeling a promise in the wrong way but i don't know how to fix it i tried using callbacks i tried using await
make the check_ip return a promise and try
function check_ip(realIP) {
return ipModel.findOne({ ip: realIP }).exec();
}

web3, truffle, nodejs error : UnhandledPromiseRejectionWarning

var web3 = require('web3'),
contract = require('truffle-contract'),
path = require('path'),
MyContractJSON = require(path.join(__dirname, '../tru_dir/build/contracts/NewCoin.json'));
var provider = new web3.providers.HttpProvider("http://localhost:8545");
var MyContract = contract(MyContractJSON);
MyContract.setProvider(provider);
MyContract.deployed().then(function(instance){
return instance.returnfive();
})
.then(function(result) {
console.log(result);
}, function(error) {
console.log(error);
});
I set this code to call a smart contract function that returns 5.
I tested it with truffle console and it works properly.
But when trying to get the same result using nodejs it crashes giving those 2 errors :
(node:6227) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): TypeError: Cannot read property 'apply' of undefined
(node:6227) DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Any idea about the issue ?
Replace MyContract definition with
const MyContract = artifacts.require("MyContractewCoin")
// You are missing this step before invoking deployer
await deployer.deploy(MyContract)
const dMyContract = await MyContract.deployed()
// now you can do stuff like
let result = await dMyContract.someContractFunction(args)

Resources