Skip to content
Advertisement

NODEJS: Return array of arrays from dialog openDirectory

I am working in a electron desktop app, and what I need to do is:

  1. Open a directory using ‘dialog.showOpenDialog’.
  2. Filter the files by their extension.
  3. Read filtered files (they have no header).
  4. Parse them into columns and return only columns 4 and 6 (coordinates).
  5. Return an array of arrays of all the files (Output example at the end).

With my little knowledge in js, this is my code so far, I’m stuck at point 4:

JavaScript

Raw file:

JavaScript

Desired Output: an array of arrays, where every array represent columns 4 and 6 from every file in the folder.

JavaScript

Advertisement

Answer

Don’t cram everything into the event handler, that’s not reusable and has horrible maintainability. Make functions that take over the fundamental parts of your task.

First, top-level dependencies go to the top.

JavaScript

A function that reads a directory and returns a promise for an array of filenames:

JavaScript

A function that takes a filename and an optional encoding, and returns a promise for the file content:

JavaScript

A function that takes a block of text and splits it into rows and columns at certain positions (since your data uses fixed-width columns):

JavaScript

And a function that picks out certain elements from an array, so you can pick the columns you want to work with from the larger set of columns the previous function returns:

JavaScript

And with all these defined, we can combine them to do something useful:

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement