How to access DOM using Node.js?

前端 未结 1 1806
一整个雨季
一整个雨季 2021-02-09 19:50

I have an editor.html that contains generatePNG function:

   
 
 
    

        
1条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-09 20:30

    The problem is that by loading an html file into cheerio (or any other node module) will not process the HTML as a browser does. Assets (such as stylesheets, images and javascripts) will not be loaded and/or processed as they would be within a browser.

    While both node.js and modern webbrowsers have the same (or similar) javascript engines, however a browser adds a lot of additional stuff, such as window, the DOM (document), etc. Node.js does not have these concepts, so there is no window.FileReader nor document.createElement.

    If the image is created entirely without user interaction (your code sample 'magically' receives the sBlob argument wich appears to be a string like data:;,) you could use a so called headless browser on the server, PhantomJS seems most popular these days. Then again, if no user interaction is required for the creation of the sBlob, you are probably better off using a pure node.js solution, e.g. How do I parse a data URL in Node?.

    If there is some kind of user interaction required to create the sBlob, and you need to store it on a server, you can use pretty much the same solution as mentioned by simply sending the sBlob to the server using Ajax or a websocket, processing the sBlob into an image and (optionally) returning the URL where to find the image.

    0 讨论(0)
提交回复
热议问题