I am trying to read a text file and convert it to a javascript object using Node JS. My file looks like as follow:
Package: libseccomp2
Depends: libc6 (>= 2.14)
Description: high level interface to Linux seccomp filter
This library provides a high level interface to constructing, analyzing
and installing seccomp filters via a BPF passed to the Linux Kernel's
prctl() syscall.
Package: libperl5.26
Depends: libbz2-1.0, libc6 (>= 2.23), libdb5.3, libgdbm-compat4, libgdbm5 (>= 1.12), zlib1g (>= 1:1.2.2.3), perl-modules-5.26 (>= 5.26.1-6ubuntu0.3)
Description: shared Perl library
This package contains the shared Perl library, used by applications
which embed a Perl interpreter.
.
It also contains the architecture-dependent parts of the standard
library (and depends on perl-modules-5.26 which contains the
architecture-independent parts).
I wanted to output it like so:
[{
Package: "libseccomp2",
Depends: ["libc6"]
Description: "high level interface to Linux seccomp filter
This library provides a high level interface to constructing, analyzing
and installing seccomp filters via a BPF passed to the Linux Kernel's
prctl() syscall."
},
{
Package: "libperl5.26",
Depends: ["libbz2-1.0", "libc6"]
Description: "high level interface to Linux seccomp filter
This library provides a high level interface to constructing, analyzing
and installing seccomp filters via a BPF passed to the Linux Kernel's
prctl() syscall."
}]
This is what I have so far but it keeps on giving me errors. Thank you in advance for your help
fs.readFile('file.txt', "utf8", (err, data) => {
if (err) {
console.error(err)
return
}
let obj = {};
let line = data.toString().split("\n");
for (let i = 0; i<line.length; i++) {
let newLine = line[i].split(":");
obj[newLine[0]] = newLine[1].split(" ");
}
console.log(obj);
})
newLine[1].split(" ")could have a problem for the lines that do not contain a ":" becausenewLine[1]will be undefined