javascript - 如何在 Deno 中写入文件?

标签 javascript deno

我试图使用 Deno.writeFile 写入文件

await Deno.writeFile('./file.txt', 'some content')

但得到以下神秘错误:
error: Uncaught TypeError: arr.subarray is not a function
    at Object.writeAll ($deno$/buffer.ts:212:35)
    at Object.writeFile ($deno$/write_file.ts:70:9)

在 Deno 中写入文件的正确方法是什么?

最佳答案

在 Deno 中写入文件有多种方法,所有方法都需要 --allow-write旗帜和意志throw如果发生错误,那么您应该正确处理错误。

使用 Deno.writeFile

此 API 采用 Uint8Array ,而不是 字符串 ,您收到该错误的原因。它还需要一个可选的 WriteFileOptions 目的

const res = await fetch('http://example.com/image.png');
const imageBytes = new Uint8Array(await res.arrayBuffer());
await Deno.writeFile('./image.png', imageBytes);

还有同步 API(它像在 Node.js 中那样阻止事件循环)。

Deno.writeFileSync('./image.png', imageBytes);

写字符串

如果你想写入一个文本文件并有一个字符串,最简单的方法是使用 Deno.writeTextFile writeFileStr 来自 std/fs .

await Deno.writeTextFile('./file.txt', 'some content');
// or if you want sync API
Deno.writeTextFileSync('./file.txt', 'some content');

// import { writeFileStr, writeFileStrSync } from 'https://deno.land/std/fs/mod.ts'
import { writeFileStr, writeFileStrSync } from 'https://deno.land/std/fs/write_file_str.ts'

await writeFileStr('./file.txt', 'some content');
writeFileStrSync('./file.txt', 'some content');

您也可以使用Deno.writeFileTextEncoder .
const encoder = new TextEncoder(); // to convert a string to Uint8Array
await Deno.writeFile('./file.txt', encoder.encode('some content'));

低级 API

使用 Deno.openDeno.writeAll (或 Deno.writeAllSync )
const file = await Deno.open('./image.png', { write: true, create: true });
/* ... */
await Deno.writeAll(file, imageBytes);
file.close(); // You need to close it!

OpenOptions here .如果你想追加你会这样做:
{ append: true }

您还可以使用更低级别的 API,例如 Deno.write Writer.write

关于javascript - 如何在 Deno 中写入文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62019830/

相关文章:

Nativescript 中的 Javascript 类/函数

typescript - Deno REPL 无法识别 TypeScript 变量声明

socket.io - 如何让 socket.io 与 deno 一起使用?

javascript - Webgl 向量数组

javascript - html - 如果鼠标点击几秒钟触发事件

javascript - 为什么更改 Canvas 大小会重置其参数?

websocket - Deno:如何将 WebSocket 与 Oak 结合使用?

javascript - 在传递参数时在 SSRS 中的新窗口中打开 URL

node.js - 有没有办法用 deno 请求 webpack

node.js - 为什么第一个函数调用的执行速度比所有其他顺序调用快两倍?