How I can create a file using multiple .chunk files? - javascript

I have more .chunk files which I fetch using node-fetch and using these files I want to create another file by "gathering them together" somehow.
I tried with this:
var fileStream = await fs.createWriteStream(`./paks/${file.Filename.slice(26)}`)
//below code is in a loop, above isn't in a loop
await fetch(chunkURL)
.then(async res => {
if(chunks.indexOf(chunk) == chunks.length - 1) await res.body.pipe(fileStream, { end: true })
else await res.body.pipe(fileStream, { end: false })
})
but the file is corrupted after it finishes, I also tried with flieStream.write(res.body, { end: true }) instead of res.body.pipe(fileStream, { end: true }) but I get the following error:
(node:12110) UnhandledPromiseRejectionWarning: TypeError [ERR_INVALID_ARG_TYPE]: The "chunk" argument must be one of type string or Buffer. Received type object
at validChunk (_stream_writable.js:265:10)
at WriteStream.Writable.write (_stream_writable.js:300:21)
at /root/api/getUpdate.js:97:87
at processTicksAndRejections (internal/process/task_queues.js:85:5)
at async /root/api/getUpdate.js:94:57
(node:12110) 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: 2)
(node:12110) [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.

Related

Getting an unhandled promise rejection when seeding a SQL database

Learning MVC, I'm trying to seed my database with dummy entries and I keep getting this error:
(node:19287) UnhandledPromiseRejectionWarning: Error
at Query.run (/Users/joshuaramat/Documents/projects/tech-blog/node_modules/sequelize/lib/dialects/mysql/query.js:52:25)
at /Users/joshuaramat/Documents/projects/tech-blog/node_modules/sequelize/lib/sequelize.js:313:28
at processTicksAndRejections (internal/process/task_queues.js:95:5)
at async MySQLQueryInterface.bulkInsert (/Users/joshuaramat/Documents/projects/tech-blog/node_modules/sequelize/lib/dialects/abstract/query-interface.js:335:21)
at async recursiveBulkCreate (/Users/joshuaramat/Documents/projects/tech-blog/node_modules/sequelize/lib/model.js:1655:25)
at async Function.bulkCreate (/Users/joshuaramat/Documents/projects/tech-blog/node_modules/sequelize/lib/model.js:1744:12)
at async seedAll (/Users/joshuaramat/Documents/projects/tech-blog/seeds/index.js:14:3)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:19287) 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:19287) [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.
the following is the code used to seed my data:
const seedUsers = require('./user-seeds');
const seedPosts = require('./post-seeds');
const seedComments = require('./comment-seeds');
const seedVotes = require('./vote-seeds');
const sequelize = require('../config/connection');
const seedAll = async () => {
await sequelize.sync({ force: true });
console.log('SEQUELIZE--------------');
await seedUsers();
console.log('USERS--------------');
await seedPosts();
console.log('POSTS--------------');
await seedComments();
console.log('COMMENTS--------------');
await seedVotes();
console.log('VOTES--------------');
process.exit(0);
};
seedAll();
The error seems to occur after the seedPosts() function is called.
Would anyone be able to help?

NodeJs,Canvas UnhandledPromiseRejectionWarning: Error: Unsupported image type

Dependency :
canvas > version: 2.6.1
node > version: 12.12.62
I am trying to do bellow :
const { createCanvas, loadImage } = require('canvas');
var image = await loadImage("png.png");
But, the same piece of code is perfectly working for *.jpeg file type.
Checked all possible points still having bellow error :
(node:2536) UnhandledPromiseRejectionWarning: Error: Unsupported image type
at setSource (********\node_modules\canvas\lib\image.js:91:13)
at Image.set (********\node_modules\canvas\lib\image.js:62:9)
at ********\landmark-detection\node_modules\canvas\index.js:34:15
at new Promise (<anonymous>)
at loadImage (********\node_modules\canvas\index.js:23:10)
at imageReconstruction (********\landmark-detection\app.js:159:22)
at ********\app.js:102:36
(node:2536) 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: 2)
(node:2536) [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.

Using loop with async/await inside loop + nodejs

Hello in my nodejs api i need fetch data inside the loop and then again need to do a loop and save a data in another table how should i achive that?
Here is some snippet that i have tried but not succeeded for the same
async myAPIname(){
let _this = this;
try {
const bets = await Bet.find({gameId:ObjectId(request.matchId)}).lean()
bets.map(async (bet) => {
let Users = await Users.findOne({_id:ObjectId(element.userId)}).lean();
Users.parentTree.map(async (user) => {
console.log(user);
// also over here based on the some calculation need to save the data in another table
})
})
} catch (error) {
_this.res.send({ status: 0, message: error });
}
}
Also in above snipped tried with foreach loop as well but not succeeded
and error from above spinet like this:
(node:30886) UnhandledPromiseRejectionWarning: ReferenceError: Cannot access 'Users' before initialization
at /var/www/html/api/app/controllers/SomeController.js:228:30
at Array.map (<anonymous>)
at SomeController.myAPIname (/var/www/html/api/app/controllers/SomeController.js:227:18)
at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:30886) 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:30886) [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:30886) UnhandledPromiseRejectionWarning: TypeError: Assignment to constant variable.
at /var/www/html/api/app/controllers/SomeController.js:220:27
at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:30886) 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: 2)
Any Help will really appreciated
I can see two problems:
firstly the await inside a map call doesn't work like you think. It will work fine in a for-of loop but not in a map, foreach etc.
https://zellwk.com/blog/async-await-in-loops/ has a good an explanation as anywhere.
Secondly where you are calling let Users = Users.findOne, the compiler thinks that Users on the left hand side of the assignment is the same as the Users on the right hand side so it complains that when its calling Users.findOne, Users isn't initialised.
to use asynchronous handling with Array.prototype.map() you have to wrap it with Promise.all() and wait for it to fulfill.
!! however notice that iterations are executed in asynchronous way, not waiting for previous iteration to settle.
const sleep = async (time = 3000) => new Promise(resolve => setTimeout(resolve, time));
(async () => {
const array = [1,3,4,2];
console.log('start', array);
const mapped =await Promise.all(array.map(async e => {
await sleep(e * 1000);
console.log(e);
return `done for ${e}`;
}));
console.log('end', mapped);
})();

UnhandledPromiseRejectionWarning: Error: Script failed to execute- Electron execute script

i try to excuteJavaScript in electron
function createTestGmail(username, password){
username = '12344444444444444444444444asdasd44444444'
testGmail = new BrowserWindow({
width: 500,
height:300,
backgroundColor:'#ccc',
title:'Kiểm tra Gmail',
webPreferences: {
nodeIntegration: true,
nativeWindowOpen: true,
}
});
testGmail.loadURL('https://example.com');
testGmail.webContents.openDevTools();
testGmail.webContents.executeJavaScript(`
console.log(`+username+`)
`)
testGmail.on('closed',()=>{
testGmail = null;
})
}
if username is a number it work correctly, if username is a string, like below, it show error code
(node:3752) UnhandledPromiseRejectionWarning: Error: Script failed to execute, this normally means an error was thrown. Check the renderer console for the error.
at WebFrame.<computed> (C:\Users\Vy\Desktop\toolyoutube\node_modules\electron\dist\resources\electron.asar\renderer\api\web-frame.js:64:33)
at WebFrame.executeJavaScript (C:\Users\Vy\Desktop\toolyoutube\node_modules\electron\dist\resources\electron.asar\common\api\deprecate.js:114:32)
at C:\Users\Vy\Desktop\toolyoutube\node_modules\electron\dist\resources\electron.asar\renderer\web-frame-init.js:11:43
at C:\Users\Vy\Desktop\toolyoutube\node_modules\electron\dist\resources\electron.asar\renderer\ipc-renderer-internal-utils.js:7:40
at new Promise (<anonymous>)
at EventEmitter.<anonymous> (C:\Users\Vy\Desktop\toolyoutube\node_modules\electron\dist\resources\electron.asar\renderer\ipc-renderer-internal-utils.js:7:9)
at EventEmitter.emit (events.js:200:13)
at Object.onMessage (C:\Users\Vy\Desktop\toolyoutube\node_modules\electron\dist\resources\electron.asar\renderer\init.js:42:16)
(node:3752) 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:3752) 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:3752) [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:3752) [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 have try with tag and it have the same problem
I saw #Bravo answered your question through a comment, but just to improve it, since you're using a template string, you could just:
testGmail.webContents.executeJavaScript(`console.log('${username}')`)
It's cleaner that way (since this is the main purpose of a template string, not only allowing to have a multiline text) and you avoid doing string concatenation with the "+" operator.
Sometimes you will mess with single quote and quote mark.
I made an util function to log everywhere.
function logEverywhere(mainWindow, message) {
if (mainWindow && mainWindow.webContents) {
mainWindow.webContents.executeJavaScript(`console.log(\`${message}\`)`);
}
}
I was taking a UDEMY course called Master Electron: Desktop Apps with HTML, JavaScript & CSS, by Ray Viljoen
And in Lesson 3.17. Session: DownloadItem, I got this same error:
(node:9552) UnhandledPromiseRejectionWarning: Error: Script failed to execute, this normally means an error was thrown. Check the renderer console for the error.
at WebFrame.e.startsWith.e.startsWith.WebFrame.<computed> [as _executeJavaScript] (electron/js2c/renderer_init.js:87:1542)
at electron/js2c/renderer_init.js:139:429
at electron/js2c/renderer_init.js:123:361
at EventEmitter.<anonymous> (electron/js2c/renderer_init.js:127:872)
at EventEmitter.emit (events.js:223:5)
at Object.onMessage (electron/js2c/renderer_init.js:115:818)
(node:9552) 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:9552) [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.
In my case I tracked the bug/problem down to some code that had a divide by zero in the event handler for DownloadItem.on. The code snippet in question is:
ses.on('will-download', (e, downloadItem, webContents) => {
let fileName = downloadItem.getFilename()
let fileSize = downloadItem.getTotalBytes() // this was zero (which caused the bug)
downloadItem.on('updated', (e, state) => {
let received = downloadItem.getReceivedBytes()
if (state === 'progressing' && received) {
// THE NEXT LINE CAUSED the divide by zero exception because fileSize was zero.
let progress = Math.round((received/fileSize)*100)
webContents.executeJavaScript(`window.progress.value = ${progress}`)
}
})
})
So my takeaway is that Electron's stack didn't help me identify where the bug is but the but was a normal coding error. Not having an exception that included a line number of my code made this particularly difficult to debug/isolate.
The underlying problem was caused by the URL being used when the course was written no longer working. From site: https://file-examples.com/.

Unhandled promise rejection when making connection to MongoDB

Hello there is my code below I have a problem since this afternoon I have two errors in the console:
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: 2)
(node:90699) [DEP0018]
DeprecationWarning: Unhandled promiserejections are deprecated. In the future, promise rejectionsthat are not handled will terminate the Node.js process witha non-zero exit code.
I switched to mongo client upstairs I think it's fine though the promised line 11 I think it's not fine
import {MongoClient} from 'mongodb'
MongoClient.connect('mongodb://localhost:27017/chatapp',
{userNewUrlParser:true});
export default class Database{
connect(){
return new Promise((resolve, reject) => {
MongoClient.connect(URL, (err, db) => {
return err ? reject(err) : resolve(db);
});
});
}
}
What's wrong? What's missing?

Categories

Resources