Search code examples
javascriptnode.jsreadfile

Save text data to nested array


I have a text file with ID's like this:

111111111
222222222
333333333

And I need to parse the txt file into an nested array, because then I need to make an INSERT to a MySQL database. So the array format has to be in this way:

data_sql = [
   ['111111111'],
   ['222222222'],
   ['333333333']
]

Now I have the next code:

var data_sql = fs.readFileSync(`./uploads/${filename}`, 'utf8').split(/\r?\n/);

But it's saving the array like this:

data_sql = [
  '111111111', 
  '222222222',
  '333333333'
]

Solution

  • You can convert every entry to an array with a single item, like this

    const formatedEntries = data_sql.map(entry => ([entry]))