Javascript: How to load data from specific parts of a text file?

Problem

Let's say I have a text file named test.txt with the following contents:

Apples.Purchased: 100
Oranges.Purchased: 202
Bananas.Purchased: 140

How can I search the text file for 'Oranges.Purchased', grab the numerical value behind it and apply it to a javascript variable?

For the record, I am using fs.write to save data:

var fs = require('fs');
fs.writeFile("test.txt", outputdata, function(err) {
        if(err) {
        console.log(err);
        } else {
            console.log("The file was saved!");
        }
}); 
Problem courtesy of: Erik Nelson

Solution

You can read the file in as text and then use a regex to find your text:

fs.readFile("test.txt", function(err, data){
  var regex = /^Oranges.Purchased: ([0-9]+)/;
  var result = regex.exec(data);
  console.log(result[1]);
});

Though you'll want to bulletproof that (check the err, don't just assume you found the text, etc).

But I don't recommend that approach in general. Why not write the file as JSON:

{
  "Apples": {
    "Purchased": 100
  },
  "Oranges": {
    "Purchased": 140
  }
  "Bananas": {
    "Purchased": 202
  }
}

Which can be generated and parsed without any string wrangling; you can just serialize your objects.

Solution courtesy of: user24359

Discussion

Parsing into JSON is the ideal solution here.

However, let me play devils advocate and provide the non-json solution, which just scans the file line-by-line, compares the keyword with the target value. If they match, then we assign the value to a variable.

Of course, this assumes that the data format is strictly as you've shown here. That is, for every line, there is a (Keyword:Value) pair. If not, this will probably raise.

target = 'Oranges.Purchased'
value_to_save = None
file = open('/tmp/contents.txt', 'r')

for i in file.readlines():
    value_pair = i.split(':')
    if value_pair[0].strip('') == target:
        value_to_save = value_pair[1].strip('')
        break

print value_to_save
Discussion courtesy of: Eudis Duran

This recipe can be found in it's original form on Stack Over Flow.