最近开始玩Deno,我按照Deno手册上的说明进行阅读和编码。
过了一段时间,我想编辑文件复制的内容,但我找不到方法。
谁能帮帮我?
for (let i = 0; i < Deno.args.length ; i++) {
let filename = Deno.args[i];
let file = await Deno.open(filename);
await Deno.copy(file, Deno.stdout);
file.close()
}
这些是我使用的终端命令。
deno run --allow-read hello.ts password.txt users.txt
还有输出。
Compile file:///home/lustepe/Dev/Practices/deno-test/hello.ts
<password>
<user>
谢谢!
现在Deno支持使用以下方法编辑JSON文件。Deno.writeFile:
const encoder = new TextEncoder();
const data = encoder.encode("Hello world\n");
await Deno.writeFile("hello1.txt", data); // overwrite "hello1.txt" or create it
await Deno.writeFile("hello2.txt", data, {create: false}); // only works if "hello2.txt" exists
await Deno.writeFile("hello3.txt", data, {mode: 0o777}); // set permissions on new file
await Deno.writeFile("hello4.txt", data, {append: true}); // add data to the end of the file
我找不到一种高度灵活的编辑文件的方法,比如通过位置、替换或regex。
那么你唯一的选择就是将文件载入内存,编辑后再将整个文件写入。
// load file
const decoder = new TextDecoder("utf-8");
const content = decoder.decode(await Deno.readFile('data.json'));
const json = JSON.parse(content);
// sets new data
json.data = "new data";
// write new data
const newtxt = JSON.stringify(json);
const newdata = new TextEncoder().encode(newtxt)
await Deno.writeFile("data.json", newdata);
let data = await Deno.readFile("data.json");
console.log(decoder.decode(data));