Read a text file and split the content into key pairs in NodeJS
To read the text file and extract the parts before and after the colon (':') character into separate variables, you can use the built-in Node.js File System (fs) module and its 'readFile' method along with the string 'split' method.
Finally, the code prints the keys and values to the console using 'console.log'.
To use this code, replace filename.txt with the name of the file you want to read, and customize the code to handle the keys and values as needed.
const fs = require('fs'); // Read the contents of the file asynchronously fs.readFile('filename.txt', 'utf-8', (err, fileContent) => { if (err) { console.error(err); return; } // Split each line into an array of key-value pairs const keyValuePairs = fileContent.trim().split(' ').map(line => line.split(':')); // Extract the keys and values into separate arrays const keys = keyValuePairs.map(pair => pair[0]); const values = keyValuePairs.map(pair => pair[1]); // Print the keys and values console.log('Keys:', keys); console.log('Values:', values); });Once the file contents are read, the code splits each line into an array of key-value pairs by calling the split method with the ':' delimiter. It then extracts the keys and values into separate arrays by using the map method to iterate over the key-value pairs and extract the first and second elements of each pair, respectively.
Finally, the code prints the keys and values to the console using 'console.log'.
To use this code, replace filename.txt with the name of the file you want to read, and customize the code to handle the keys and values as needed.
Comments (0)