Home > Mobile >  is there a way to read data from txt file and use this data in a object?
is there a way to read data from txt file and use this data in a object?

Time:12-09

I have a txt file with people's name,i would like to put that data into a javascript/Json object,i would then import that object with ES6 modules. This data would be used to render html elements with that data and then like searching on a search bar,filtering by their name,sex etc... example:

txt.file:
men:
john doe
antony rewasd
randomName lastName
............
............
women:
hailey Coleman
mary johnson
............
...........
...........
output:
const people = 
{
      women:
      [
            { 
                name:'whatever',
                lastName:'______',
                sex:'W',
            },
            { 
                name:'whatever',
                lastName:'______',
                sex:'W',
            },
              .............................
            .............................
            .............................
      ],
      men:
      [
            { 
                name:'whatever',
                lastName:'______',
                sex:'M',
            },
            { 
                name:'whatever',
                lastName:'______',
                sex:'M',
            },
            .............................
            .............................
            .............................
      ]
}

CodePudding user response:

I use the file name text.txt The files content are in a stringified JSON:

{"men": ["a","b"]}

The code to access this looks like this:

const fs = require('fs')
const data = fs.readFile('test.txt', (err, data) => {
    if (err) throw err;
    data = JSON.parse(data.toString())
    // Write code here to make use of the data
    console.log(data)
})

The console logs this:

{ men: [ 'a', 'b' ] }

Then you can use the received object from the textfile to fill in your objects in the callback function

CodePudding user response:

That was an interesting question to combine

  1. reading from a plain file
  2. parsing lines
  3. changing behaviours based on different lines

Please change separator and fileName based on your settings:

const fs = require("fs");
const separator = "\r\n";
const fileName = "txt.file";
const array = fs.readFileSync(fileName).toString().split(separator);

const people = { women: [], men: [] };
const addMan = (collection, item) => {
  collection.men.push({ ...item, sex: "M" });
};
const addWoman = (collection, item) => {
  collection.women.push({ ...item, sex: "W" });
};
let addPerson = () => {};

for (line of array) {
  if (line == "men:") addPerson = addMan;
  else if (line == "women:") addPerson = addWoman;
  else {
    const [firstName, ...lastName] = line.split(" ");
    addPerson(people, { name: firstName, lastName: lastName.join("") });
  }
}

console.log(people);
  • Related