GridFSBucketReadStream error: cannot read property 'write' of null - node.js

I'm using mongodb module to download a file from gridfs.
Here's the code -
import { Db, Server, GridFSBucket } from 'mongodb';
let gfs = new GridFSBucket(new Db(<db_name>, new Server("127.0.0.1", 27017)), {"bucketName": "fs"});
let readStreamData = gfs.openDownloadStream(<ObjectId>);
The output is the following error -
error occurred in downloadreport TypeError: Cannot read property 'write' of null
at Object.query (C:\project\node_modules\mongodb\lib\core\wireprotocol\query.js:29:19)
at Server.query (C:\project\node_modules\mongodb\lib\core\topologies\server.js:639:16)
at FindOperation.execute (C:\project\node_modules\mongodb\lib\operations\find.js:24:12)
at C:\project\node_modules\mongodb\lib\operations\execute_operation.js:168:15
at Server.selectServer (C:\project\node_modules\mongodb\lib\core\topologies\server.js:827:3)
at Server.selectServer (C:\project\node_modules\mongodb\lib\topologies\topology_base.js:363:32)
at executeWithServerSelection (C:\project\node_modules\mongodb\lib\operations\execute_operation.js:150:12)
at executeOperation (C:\project\node_modules\mongodb\lib\operations\execute_operation.js:81:16)
at Cursor._initializeCursor (C:\project\node_modules\mongodb\lib\core\cursor.js:545:7)
at Cursor._initializeCursor (C:\project\node_modules\mongodb\lib\cursor.js:191:11)
at nextFunction (C:\project\node_modules\mongodb\lib\core\cursor.js:748:10)
at Cursor._next (C:\project\node_modules\mongodb\lib\core\cursor.js:202:5)
at nextObject (C:\project\node_modules\mongodb\lib\operations\common_functions.js:234:10)
at NextOperation.execute (C:\project\node_modules\mongodb\lib\operations\next.js:26:5)
at executeOperation (C:\project\node_modules\mongodb\lib\operations\execute_operation.js:83:26)
at Cursor.next (C:\project\node_modules\mongodb\lib\cursor.js:217:12)
C:\project\node_modules\mongodb\lib\utils.js:133
throw err;
does anyone know what is it that I'm doing wrong?
PS: I also want to download and save the data I receive in a pdf file (the data is pdf content already). How can I achieve this?

Related

discord.js client.off fails

I want to reload the code used for events in discord.js. The code is currently stored in a collection (the same way as commands in the discord.js guide). I have the following code:
client.events.delete(args[0]);
const file = require(`../events/${args[0]}.js`);
client.off(file.name, (...eventArgs) => this.events.get(file.name).run(this.client, this.shared, ...eventArgs));
message.reply(`Removed ${file.name} event.`);
The events are added to the listener using this:
for (const file of readdirSync('./events').filter(check => check.endsWith('.js'))) {
const event = require(`./events/${file}`);
this.shared.logger.log('info', `Loaded event ${event.name}`);
this.shared.events.set(event.name, event);
}
this.events.forEach(event => {
const file = require(`./events/${event.name}.js`);
this.client.on(file.name, (...eventArgs) => this.events.get(file.name).run(this.client, this.shared, ...eventArgs));
});
This runs without error, then when the event that was removed is triggered I get the following error in console:
TypeError: Cannot read property 'run' of undefined
at Client.<anonymous> (E:\Files\code\bot\index.js:85:73)
at Client.emit (events.js:315:20)
at WebSocketManager.debug (E:\Files\code\bot\node_modules\discord.js\src\client\websocket\WebSocketManager.js:125:17)
at WebSocketShard.debug (E:\Files\code\bot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:168:18)
at WebSocketShard.sendHeartbeat (E:\Files\code\bot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:557:10)
at Timeout._onTimeout (E:\Files\code\bot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:529:73)
at listOnTimeout (internal/timers.js:554:17)
at processTimers (internal/timers.js:497:7)
I assume this is caused because client.off isn't removing the event from the listener, but is deleting it from the collection, meaning that it is undefined when that event is triggered and the error is caused.
Discord event is always on. If you try to remove it, it will still persist until you've terminated the program, so you'd get the error. Try using this.client.once instead, and recall it when the desired event is needed.

pdf-merger-js throws a TypeError and Fails

I have been using pdf-merger-js to merge PDF files for a while now. I have used it with PDF files I have generated from HTML files and with PDF files I did not create.
Then I started getting the error:
Uncaught TypeError: Cannot read property 'compressed' of undefined
and the merger would fail. I tried different versions of node with the same results. The version that has been working is node v12.19.1.
/* /path/to/project/mpdf.js */
const PDFMerger = require('pdf-merger-js');
const path = require('path');
(async () => {
try {
const pdfs = ['pdf1.pdf','pdf2.pdf','pdf3.pdf','pdf4.pdf','pdf5.pdf'];
const merger = new PDFMerger();
pdfs.map(f => path.resolve(__dirname, "subfolder", f)
.forEach(pdf => merger.add(pdf));
//^^^Error occurs on this line
await merger.save('all-merged.pdf');
} catch( err ) {
console.log( err );
}
})();
Has any of you worked with pdf-merger-js and, have you encountered the above error? If so, how did you resolve the error?
Stack Trace
TypeError: Cannot read property 'compressed' of undefined
at parseObject (/path/to/project/node_modules/pdfjs/lib/object/reference.js:81:15)
at PDFReference.get [as object] (/path/to/project/node_modules/pdfjs/lib/object/reference.js:15:17)
at new ExternalDocument (/path/to/project/node_modules/pdfjs/lib/external.js:20:42)
at PDFMerger._addEntireDocument (/path/to/project/node_modules/pdf-merger-js/index.js:29:15)
at PDFMerger.add (/path/to/project/node_modules/pdf-merger-js/index.js:11:12)
at /path/to/project/app3.js:10:34
at Array.forEach (<anonymous>)
at /path/to/project/app3.js:10:12
at processTicksAndRejections (internal/process/task_queues.js:97:5)
Update
I have encountered another set of PDF files that are throwing a different error on the same line:
TypeError: Cannot read property 'object' of undefined
at new ExternalDocument (/path/to/project/node_modules/pdfjs/lib/external.js:20:42)
at PDFMerger._addEntireDocument (/path/to/project/node_modules/pdf-merger-js/index.js:29:15)
at PDFMerger.add (/path/to/project/node_modules/pdf-merger-js/index.js:11:12)
at /path/to/project/app3.js:10:34
at Array.forEach (<anonymous>)
at /path/to/project/app3.js:10:12
at processTicksAndRejections (internal/process/task_queues.js:97:5)
I got the same error whenever I used compressed PDFs for merging. Seems to be a bug in the underlying pdfjs library according to a Github issue in the pdf-merger-js repository.
Not the kind of answer I was looking for ....
If you flatten the files prior to merging them then the merging works fine. This seems to resolve the two errors I encountered.
I am using pdf-flatten just before merging as follows:
const fsp = require('fs').promises;
const flattener = require('pdf-flatten');
//....
const pdfs = ['pdf1.pdf','pdf2.pdf','pdf3.pdf','pdf4.pdf','pdf5.pdf'];
for(pdf of pdfs) {
const pdfB = await fsp.readFile(path.resolve(__dirname,"subfolder", pdf));
const pdfFlat = await flattener.flatten(pdfB, {density: 300});
await fsp.writeFile(path.resolve(__dirname,"subfolder", `flattened_${pdf}`), pdfFlat);
}
//....merge the flattened files:
//.... pdfs.map(p => `flattened_${p}`).....

Type Error: Cannot read property 'hasListCollectionsCommand' of null

I'm trying to get all collection names in mongodb (v4.0.2) and using mongodb#3.1.10 nodejs driver. From the docs, I can see that listCollections might work, but running the following:
const Db = require('mongodb').Db
const Server = require('mongodb').Server
const db = new Db(dbName, new Server(host, port, options), {})
db.listCollections().toArray((error, collectionNames) => {
console.error(error)
console.log(JSON.stringify(collectionNames))
})
… leads to this error:
if (this.serverConfig.capabilities().hasListCollectionsCommand) {
TypeError: Cannot read property 'hasListCollectionsCommand' of null
at Db.listCollections ({path}/node_modules/mongodb/lib/db.js:493:39)
at db.createCollection ({path}/sampleMongoDB.js:19:8)
at err ({path}/node_modules/mongodb/lib/utils.js:415:14)
at executeCallback ({path}/node_modules/mongodb/lib/utils.js:404:25)
at executeOperation ({path}/node_modules/mongodb/lib/utils.js:422:7)
at Db. ({path}/node_modules/mongodb/lib/db.js:431:12)
at Db.deprecated [as createCollection] ({path}/node_modules/mongodb /lib/utils.js:661:17)
at Object.< anonymous > ({path}/sampleMongoDB.js:18:6)
at Module._compile (module.js:653:30)
at Object.Module._extensions..js (module.js:664:10)
My questions are:
Is there a docs site for MongoDB NodeJs drivers where we can refer examples from?
If not, what's the correct way to query?
I was able to work it out. The MongoClient's instance returns a db instance, which inturn helps run mongodb.Db methods.
Here's a sample code that worked (Ref. to MongoDB guides)
const options = {
useNewUrlParser: true, // Add this, if you wish to avoid {https://stackoverflow.com/questions/50448272/avoid-current-url-string-parser-is-deprecated-warning-by-setting-usenewurlpars} issue
}
const client = new MongoClient(connectionUri, options)
return client.connect().then(() => {
const db = client.db(dbName)
return db.listCollections()
.toArray()
.then((collections) => {
// Collections array
})
})
#Community mods - if required, kindly close this question.

vue/test-utils: Add localVue and stubs.transition to mount() but throw error like 'Cannot read property '_transitionClasses' of undefined'

"element-ui": "2.4.6"
"#vue/test-utils": "^1.0.0-beta.29"
I want to bind Element-ui to mount so at the beginning i wirite as:
import { mount, createLocalVue, shallowMount, config } from '#vue/test-utils'
import Element from 'element-ui'
const localVue = createLocalVue()
localVue.use(Element)
And my primary code:
const wrapper = mount(List, {
localVue
})
setTimeout(() => {
expect(wrapper.contains(OperationColumn)).toBe(true)
done()
})
And after running i got:
TypeError: Cannot read property '$el' of undefined
at VueComponent.mounted (F:\workspace\HaiShangEdit\node_modules\element-ui\lib\select.js:1280:54)
at invokeWithErrorHandling (F:\workspace\HaiShangEdit\node_modules\vue\dist\vue.runtime.common.dev.js:1843:57)
at callHook (F:\workspace\HaiShangEdit\node_modules\vue\dist\vue.runtime.common.dev.js:4157:7)
at Object.insert (F:\workspace\HaiShangEdit\node_modules\vue\dist\vue.runtime.common.dev.js:3108:7)
at invokeInsertHook (F:\workspace\HaiShangEdit\node_modules\vue\dist\vue.runtime.common.dev.js:6266:28)
at VueComponent.patch [as __patch__] (F:\workspace\HaiShangEdit\node_modules\vue\dist\vue.runtime.common.dev.js:6483:5)
at VueComponent.Vue._update (F:\workspace\HaiShangEdit\node_modules\vue\dist\vue.runtime.common.dev.js:3886:19)
at VueComponent.updateComponent (F:\workspace\HaiShangEdit\node_modules\vue\dist\vue.runtime.common.dev.js:4007:10)
at Watcher.get (F:\workspace\HaiShangEdit\node_modules\vue\dist\vue.runtime.common.dev.js:4405:25)
at new Watcher (F:\workspace\HaiShangEdit\node_modules\vue\dist\vue.runtime.common.dev.js:4394:12)
at mountComponent (F:\workspace\HaiShangEdit\node_modules\vue\dist\vue.runtime.common.dev.js:4014:3)
at VueComponent.Object.<anonymous>.Vue.$mount (F:\workspace\HaiShangEdit\node_modules\vue\dist\vue.runtime.common.dev.js:8327:10)
at mount (F:\workspace\HaiShangEdit\node_modules\#vue\test-utils\dist\vue-test-utils.js:8649:21)
at Object.<anonymous> (F:\workspace\HaiShangEdit\test\pictureLibrary\list.spec.js:45:22)
at Object.asyncJestTest (F:\workspace\HaiShangEdit\node_modules\jest-jasmine2\build\jasmine_async.js:108:37)
at resolve (F:\workspace\HaiShangEdit\node_modules\jest-jasmine2\build\queue_runner.js:56:12)
at new Promise (<anonymous>)
at mapper (F:\workspace\HaiShangEdit\node_modules\jest-jasmine2\build\queue_runner.js:43:19)
at promise.then (F:\workspace\HaiShangEdit\node_modules\jest-jasmine2\build\queue_runner.js:87:41)
at process._tickCallback (internal/process/next_tick.js:68:7)
console.error node_modules/#vue/test-utils/dist/vue-test-utils.js:1421
[vue-test-utils]: update has been removed from vue-test-utils. All updates are now synchronous by default
And after google i find it was a bug from Element-ui so i change my part code like:
const wrapper2 = mount(List, {
localVue,
sync: true,
stubs: {
transition: false
}
})
But it still failed with more errors:
[Vue warn]: Error in callback for watcher "options": "TypeError: Cannot read property 'querySelectorAll' of undefined"
TypeError: Cannot read property 'querySelectorAll' of undefined
at VueComponent.options (F:\workspace\HaiShangEdit\node_modules\element-ui\lib\element-ui.common.js:8577:29)
TypeError: Cannot set property 'documentHandler' of undefined
at update (F:\workspace\HaiShangEdit\node_modules\element-ui\lib\utils\clickoutside.js:64:29)
[Vue warn]: Error in created hook: "TypeError: Cannot read property '_transitionClasses' of undefined"
TypeError: Cannot read property '_transitionClasses' of undefined
at Array.updateClass (F:\workspace\HaiShangEdit\node_modules\vue\dist\vue.runtime.common.dev.js:6733:28)
I'm quite confused about vue/test-utils cause i'm a new learner,so it would be grateful if anyone can help me solve this problem.By the way, should i learn jest before i start to write vue unit test with vue/test-utils?

mongodb connect by mongoskin error

I have tried below mentioned code to connect mongo db using mongoskin node module
var mongo = require('mongoskin');
var db = mongo.db("localhost:27017/mydb");
db.bind('mycollection');
db.mycollection.find().toArray(function(err, items) {
console.log(items)
db.close();
});
I am getting below mentioned error.
/usr/local/lib/node_modules/mongoskin/node_modules/mongodb/lib/mongodb/connection/url_parser.js:15
throw Error("URL must be in the format mongodb://user:pass#host:port/dbnam
^
Error: URL must be in the format mongodb://user:pass#host:port/dbname
at Error (<anonymous>)
at exports.parse (/usr/local/lib/node_modules/mongoskin/node_modules/mongodb/lib/mongodb/connection/url_parser.js:15:11)
at Function.MongoClient.connect (/usr/local/lib/node_modules/mongoskin/node_modules/mongodb/lib/mongodb/mongo_client.js:164:16)
at SkinClass.SkinDb._open (/usr/local/lib/node_modules/mongoskin/lib/db.js:36:25)
at SkinClass.open (/usr/local/lib/node_modules/mongoskin/lib/utils.js:162:14)
at SkinClass.SkinCollection._open (/usr/local/lib/node_modules/mongoskin/lib/collection.js:49:17)
at SkinClass.open (/usr/local/lib/node_modules/mongoskin/lib/utils.js:162:14)
at SkinClass.SkinCursor._open (/usr/local/lib/node_modules/mongoskin/lib/cursor.js:28:25)
at SkinClass.open (/usr/local/lib/node_modules/mongoskin/lib/utils.js:162:14)
at SkinClass.(anonymous function) [as toArray] (/usr/local/lib/node_modules/mongoskin/lib/utils.js:116:14)
In that error it has mentioned enter username and password.I dont have username and pasword.What i have to enter for that please help me.
My mongodb version is v1.8.2,
node version is v0.10.28,
mongoskin version is v1.4.4.
The error says:
throw Error("URL must be in the format mongodb://user:pass#host:port/dbnam")
Have you tried adding the protocol? (i.e.:)
var db = mongo.db("mongodb://localhost:27017/mydb");
The answer lies in the error itself :
throw Error("URL must be in the format mongodb://user:pass#host:port/dbnam
^
Error: URL must be in the format mongodb://user:pass#host:port/dbname
In case you didn't understand , kindly do as mentioned below :
var mongo = require('mongoskin');
var db = mongo.db("mongodb://localhost:27017/mydb");
db.bind('mycollection');
db.mycollection.find().toArray(function(err, items)
{
console.log(items)
db.close();
});

Resources