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
There’s no specific API for these methods
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 arrayTo 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().
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.
I see, so there's no other way but to process the whole file anyway. Thanks
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
I haven't used this myself so I couldn't tell you the details, I'm afraid.
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.
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-fileCraig'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.
Of course, but it still requires looping through all lines when it comes to inserting and deleting.
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.