0

I've seen this question a few times but all seem to ask questions differently than mine thus I'm having a few problems trying to wrap my head around how i'd handle what i'm trying to do.

I have a file that I create in node, basically a JSON object stringified.

I read the file like so :

fs.readFile('data.txt', 'utf-8', function (err, data) {
    console.log(data.search("generated_images"));

    if (err) {
        return console.error(err);
    }
});

How can I do a search on the text file I have and find every time generated_images has been used in there?

I'm basically trying to get the word generated_images then grab characters after it so...

Everytime generated_images is used, count 80 characters after and write it to a new array or new text file I can read.

4
  • This sounds like an XY Problem - why not just parse the stringified JSON and traverse the object normally? Commented Jun 13, 2016 at 11:45
  • It doesn't contain JSON anymore, because I stringified it when writing it to a new file. I did fs.writeFile('data.txt', JSON.stringify(data), function(err) {) Commented Jun 13, 2016 at 11:47
  • 2
    The output of JSON.stringify() is JSON. In other words, JSON is a string representation of an object. (There's no such thing as a "JSON object".) You use JSON.parse() to turn the string back into an actual object. Commented Jun 13, 2016 at 11:49
  • if data.txt contains json data, you can use JSON.parse(data) to get json object and traverse object normally to get your job done. Commented Jun 13, 2016 at 12:27

1 Answer 1

1

You have some discussion of JSON above, but in your question you specifically ask how to grab "80 chars after"... A regular expression is a fast way to achieve this. Consider this input text:

var data = 'asdf qwer asdf asfwe generated_images 12345678901234567890123456789012345678901234567890123456789012345678901234567890 adsf weqr asdfjkaekl zdfjhasdf generated_images abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzab';

Then this code will return the results shown::

data.match(/generated_images .{0,80}/g);

['generated_images 12345678901234567890123456789012345678901234567890123456789012345678901234567890',
 'generated_images abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzab']
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.