KaKi87
KaKi872y 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
11 Replies
mxdvl
mxdvl2y ago
There’s no specific API for these methods
mxdvl
mxdvl2y 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
mxdvl2y 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 🤖2y 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
KaKi872y ago
I see, so there's no other way but to process the whole file anyway. Thanks
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
KaKi87
KaKi872y 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
cdoremus2y 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
KaKi872y ago
Of course, but it still requires looping through all lines when it comes to inserting and deleting.
Doctor 🤖
Doctor 🤖2y 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.