vscode.workspace.fs.writeFile other than text #1268
-
hi VSCode Community, I'm trying to save some binary files from the web into the user workspace, but when I try to write the files with vscode.workspace.fs.writeFile() I'm getting corrupt files. For example I cannot store a PDF, SVG, PNG, JPEG or other file formats. How are you solving for this? const fmPath = `${getWorkspaceUri().fsPath}/_files/Icons/firebase.png`
const res = await fetch(`https://www.gstatic.com/devrel-devsite/prod/vc3f2c9e1a38bbf17d13dba368cd3cbb8fa1d62d936b55c84ca4c54c7df2da66a/firebase/images/lockup.svg`)
//console.log("GGL", await res.blob())
const data = await (await res.blob()).stream().getReader().read()
if (data.done) throw new Error('Stream was already closed or empty')
if (data.value) {
vscode.workspace.fs.writeFile(
getWorkspaceUri().with({
path: fmPath,
}),
data.value
)
logger.notice(`📃 Downloaded ${fmPath}`)
} |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
Hi Miciurash, When saving binary files using vscode.workspace.fs.writeFile(), it's crucial to ensure that the data is correctly formatted as a Uint8Array because this method expects data in this format. The issue you're encountering with corrupt files likely stems from not converting the fetched data into a Uint8Array properly before writing. Here's how you can solve this issue:
Try the following (suggested modified code from Copilot) as a guideline. Let me know if it helps. -r const fmPath = `${getWorkspaceUri().fsPath}/_files/Icons/firebase.png`;
const res = await fetch(`https://www.gstatic.com/devrel-devsite/prod/vc3f2c9e1a38bbf17d13dba368cd3cbb8fa1d62d936b55c84ca4c54c7df2da66a/firebase/images/lockup.svg`);
// Convert the response to a Blob, then to an ArrayBuffer, and finally to a Uint8Array
const blob = await res.blob();
const arrayBuffer = await blob.arrayBuffer();
const data = new Uint8Array(arrayBuffer);
// Ensure data is not empty
if (data.length === 0) throw new Error('Downloaded data is empty');
// Write the file
await vscode.workspace.fs.writeFile(
vscode.Uri.file(fmPath),
data
);
logger.notice(`📃 Downloaded ${fmPath}`); |
Beta Was this translation helpful? Give feedback.
-
Thank you @theReynald, your suggestion worked! |
Beta Was this translation helpful? Give feedback.
Hi Miciurash,
When saving binary files using vscode.workspace.fs.writeFile(), it's crucial to ensure that the data is correctly formatted as a Uint8Array because this method expects data in this format. The issue you're encountering with corrupt files likely stems from not converting the fetched data into a Uint8Array properly before writing.
Here's how you can solve this issue:
Try the following (suggested modified code from Copilot) as a guideline…