KaKi87
KaKi873y ago

File line operations

Hello, How to perform the following file manipulations in Deno ? - Read the nth line - Remove the nth line - Add a line before the nth line nth can he anything including and between first and last. Thanks
12 Replies
mxdvl
mxdvl3y ago
There’s no specific API for these methods
mxdvl
mxdvl3y ago
Assuming that performance is not your primary concern and you are familiar with JavaScript arrays, the docs should give you enough information You can, for example, split the file content on the new line character \n and modify the nth item in the array
mxdvl
mxdvl3y ago
To mutate and array and insert a new line you can use splice: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice
Array.prototype.splice() - JavaScript | MDN
The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place. To access part of an array without modifying it, see slice().
Doctor 🤖
Doctor 🤖3y ago
I’d probably create a function that reads a file line by line and writes it down to a new file. It takes a function as an argument and executes it when it gets to the desired range. Then writes the rest of the file after the range and renames it to the old one deleting the old one. There might be a better way. But that’s how I’d solve your problem.
KaKi87
KaKi87OP3y ago
I see, so there's no other way but to process the whole file anyway. Thanks
Moomoo
Moomoo3y ago
If you want to avoid reading the whole file, you could use a readable stream to read it in chunks: https://deno.land/api@v1.27.1?s=Deno.FsFile#prop_readable
Deno
Deno.FsFile | Runtime APIs | Deno
The Deno abstraction for reading and writing files.
Moomoo
Moomoo3y ago
I haven't used this myself so I couldn't tell you the details, I'm afraid.
KaKi87
KaKi87OP3y ago
I mean yes I can choose not to read it the whole file at once but I will still need to read the whole file in the end, even if in chunks.
cdoremus
cdoremus3y ago
I wrote a blog post on processing CSV data, and here is the section where I show how to use a TextProtoReader to read a file one line at a time: https://deno-blog.com/Processing_CSV_files_with_Deno.2022-09-20#reading-data-from-a-large-csv-file
Craig's Deno Diary
Craig's Deno Diary is a blog that covers the JavaScript and TypeScript runtime Deno and focuses on how to write Deno programs and use Deno libraries.
KaKi87
KaKi87OP3y ago
Of course, but it still requires looping through all lines when it comes to inserting and deleting.
Doctor 🤖
Doctor 🤖3y ago
Depending on what's stored in the files, you could opt for a database instead which offers insertion, deletion and replacement of entries. Or you could opt for smaller files. Breaking the one thing up over many files.