在node.js中,如何将fetch中的二进制数据写入文件?

vjhs03f7  于 2023-11-17  发布在  Node.js
关注(0)|答案(3)|浏览(176)

假设我想将图像保存到磁盘。

var path = require('path');
var webdriver = require("selenium-webdriver");
var chrome = require('selenium-webdriver/chrome');
var By = webdriver.By;
var until = webdriver.until
const fs = require("fs");
var o = new chrome.Options();
o.addArguments("--disable-web-security");
var browser = new webdriver.Builder().forBrowser('chrome').setChromeOptions(o).build();

fetch("https://upload.wikimedia.org/wikipedia/commons/9/9d/Blue_Flower.png");

字符串
这不起作用,fetch没有定义。
然后我尝试将fetch添加到browser.executeScript中

var promise1 = browser.executeScript(`return fetch("https://upload.wikimedia.org/wikipedia/commons/9/9d/Blue_Flower.png");`)
promise1.then((x) => x.arrayBuffer()).then((buffer) => fs.writeFile("flower.png", buffer, () => console.log("done")))


这不起作用。事实证明,当executeScript返回一个对象时,对象中的所有函数都被替换为{}。
然后我尝试从executeScript返回缓冲区。

var promise1 = browser.executeScript(`return fetch("https://upload.wikimedia.org/wikipedia/commons/9/9d/Blue_Flower.png").then((x) => x.arrayBuffer());`)
promise1.then((buffer) => fs.writeFile("flower.png", buffer, () => console.log("done")))


还是不行。原来buffer变成了{};
有没有什么方法可以让我访问arrayBuffer,而不会在它从executeScript出来后变成{}?

kb5ga3dv

kb5ga3dv1#

const res = await fetch(url);
const fileWriteStream = fs.createWriteStream('/directory/path.ext');
res.body.pipe(fileWriteStream);

字符串

oyjwcjzk

oyjwcjzk2#

我使用base64来实现,我使用了this answer的代码:

var promise1 = browser.executeScript(`return fetch("https://upload.wikimedia.org/wikipedia/commons/9/9d/Blue_Flower.png").then((x) => x.arrayBuffer()).then(function(buffer){
    var blob = new Blob([buffer])

var reader = new FileReader();
reader.readAsDataURL(blob);
    
    return reader
}).then(function(reader){
    return new Promise(function(x, y){
        this.addEventListener("loadend", function(){
            x(this);
        }.bind(this))
    }.bind(reader)); 
}).then(function(reader){
    return reader.result.slice(reader.result.indexOf(",")+1);
})  
`)
promise1.then(function(b64data){
    let buff = Buffer.from(b64data, 'base64');
    fs.writeFileSync("flower.png", buff);
    console.log("done");
})

字符串

pb3skfrl

pb3skfrl3#

在NodeJS 21.2.0中,我是这样做的:

const response = await fetch(url);

const readableStream = Readable.fromWeb(response .body);

const fileWriteStream = createWriteStream(path);
readableStream.pipe(fileWriteStream);

字符串

相关问题