How to use File
in CommonJS?馃槩
#1529
-
Discussed in #1527Originally posted by KairuiLiu March 30, 2022 const fetch = (...args) =>
import('node-fetch').then(({ default: fetch }) => fetch(...args)); I try to use File in CommonJs const fetch = (...args) =>
import('node-fetch').then(({ default: fetch }) => fetch(...args));
const File = (...args) =>
import('node-fetch').then(({ File }) => File(...args));
function reqImage(url) {
return fetch(url)
.then((d) => d.buffer())
.then((b) => new File([b], 'abc.png'), { type: 'image/png' });
} and get error .then((b) => new File([b], 'abc.png'), { type: 'image/png' });
^
TypeError: File is not a constructor any one can help to know how to use File?馃槩 |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments
-
the And the also, the use of Here are some solutions: const fileFrom = (...args) => import('node-fetch').then(({ File }) => new File(...args))
function reqImage(url) {
return fetch(url)
.then(res => res.blob())
.then(blob => fileFrom([blob], 'abc.png'), { type: blob.type })
} |
Beta Was this translation helpful? Give feedback.
-
another possible solution i have recently done in a cjs project that was not able to update to esm was to make a own lite module that returned an empty object that later inherited all node-fetch options after the module have been imported, something like this lazy loader: // util/fetch.cjs
const obj = {}
const p = import('node-fetch').then(mod => {
const { default: fetch, ...rest} = mod
Object.assign(obj, { fetch }, rest)
})
obj.fetch = (...args) => p.then(obj.fetch(...args))
obj.ready = p
module.exports = obj then i could use it like this: const util = require('./util/fetch.cjs')
// at first util is just an empty object with { fetch: asyncFn & ready: Promise }
util.fetch(url)
/*
when the module have loaded, then it will perform the fetch and all other
things have been attached to the `obj`
so at this point you no longer have to use async loading of our sub modules,
since File, FormData and everything else is added onto the `obj` after the
node-fetch have been successfully lazy loaded.
*/
.then(res => res.blob())
.then(blob => new util.File([blob], 'sample.txt', blob )) |
Beta Was this translation helpful? Give feedback.
-
you could also ofc just do: async function reqImage(url) {
const { default: fetch, File } = await import('node-fetch')
const res = await fetch(url)
const blob = await res.blob()
return new File([blob], 'abc.png'), { type: blob.type })
} |
Beta Was this translation helpful? Give feedback.
you could also ofc just do: