hbi99 / defiant.js

http://defiantjs.com
GNU Affero General Public License v3.0
913 stars 91 forks source link

Can defiant be used inside a web worker ? #102

Closed v1nce closed 6 years ago

v1nce commented 6 years ago

I don't get it, When I read the following line I thought web workers were supported

1.2.6 Snapshot can be created with web worker (x10.js)

but I can't make it run inside my own web worker.

When importing 2.0.4 using

importScripts(
    './defiant.js'  
);

it failed around line 690 for Defiant.node.selectNodes = function(XNode, XPath) {

because Defiant is undefined. You exported Defiant namespace at line 275 using window.Defiant = module.exports = Defiant;

but when running in a context of a web worker, window is just a empty object you instanciated before calling the method typeof window !== 'undefined' ? window : {}

So when exiting the function window object is no more. And that's why it failed. I tried to fake a global window object but then it will fail later in xmlfromstring when trying to instanciate a DOMParser.

Can defiant be used inside a web worker ?

hbi99 commented 6 years ago

Hi @v1nce, Defiant can not work inside of a web worker. It does utilise web worker to do stuff inside a web worker - hence executing the work faster and also in a separate threat then the UI thread.

As you may know, code executed inside web workers are strict and parts of Defiant is nowhere near that strict and uses mechanisms that are not allowed inside web workers.

Best regards

v1nce commented 6 years ago

This was the conclusion I reached.

Maybe you can write it in the readme ?

AFAIK there's no other "XPATH evaluator" js library that works in a web worker. I was looking for a worker solution because I'm unzipping and parsing large number of xml files. Looks like I need to find another way to do it.

Anyway thanks for your cool library.

hbi99 commented 6 years ago

Hi again, I am pretty sure you can not evaluate and/or manipulate XML in web worker context. Check out this documentation: https://www.html5rocks.com/en/tutorials/workers/basics/

Is your script running in browser or in Node environment? If in browser, Deifant is definitely not the lib you are looking for, since Defiants main purpose is to search in JSON data and transforming with XSLT (which the documentation states). And in browser environment, it is easier to execute XPath on XML files without libraries...

If in Node environment - Defiant might help you. In version > 2.0, there is support for async/await functions. Though this does not need to be executed in web worker context.