Scott Scott - 4 months ago 28
Node.js Question

Finding the index of the last import statement

I'm reading a file using Node's

fs.readFileSync(file)
. I need to find the index of the last occurrence of an import statement.

The js file that I'm reading will look something like:

import React from 'react';
import { FlowRouter } from 'meteor/kadira:flow-router';
import { mount } from 'react-mounter';
import { AppLayout } from '../../ui/layouts/AppLayout';
import HomePage from '../../ui/pages/HomePage';

FlowRouter.route('/', {
name: 'home',
action() {
mount(AppLayout, {
content: (<HomePage />)
});
}
});


So in this particular case, I would need to find the index of the semi-colon for this import statement:
import HomePage from '../../ui/pages/HomePage';
since it's the last one.

I've looked into
str.lastIndexOf(searchValue[, fromIndex])
but it takes a string as the
searchValue
, and in this case I need to pass in a regex.

It seems like I need a regex that will lookup in reverse.

How do I match and get the index of the last occurrence of import?

Answer

I think what you want to find is the last line starting with import and insert another line after it. There are several ways.

Splice & indexOf:

// splice code from http://stackoverflow.com/a/4314050/3832970
String.prototype.splice = function(idx, rem, str) {
    return this.slice(0, idx) + str + this.slice(idx + Math.abs(rem));
};
var input = "import React from 'react';\nimport { FlowRouter } from 'meteor/kadira:flow-router';\nimport { mount } from 'react-mounter';\nimport { AppLayout } from '../../ui/layouts/AppLayout';\nimport HomePage from '../../ui/pages/HomePage';\n\nFlowRouter.route('/', {\n  name: 'home',\n  action() {\n    mount(AppLayout, {\n      content: (<HomePage />)\n    });\n  }\n});";
var strt = input.lastIndexOf("\nimport ");
strt = input.indexOf("\n", strt+1);
document.body.innerHTML = "<pre>" +  input.splice(strt+1, 0, "import Example from \'../../example\';\n") + "</pre>";

Regex:

var input = "import React from 'react';\nimport { FlowRouter } from 'meteor/kadira:flow-router';\nimport { mount } from 'react-mounter';\nimport { AppLayout } from '../../ui/layouts/AppLayout';\nimport HomePage from '../../ui/pages/HomePage';\n\nFlowRouter.route('/', {\n  name: 'home',\n  action() {\n    mount(AppLayout, {\n      content: (<HomePage />)\n    });\n  }\n});";
document.body.innerHTML = "<pre>"
   + input.replace(/^(?:[\s\S]*\n)?import .*(?:\r?\n|\r)/, 
     '$&import Example from \'../../example\';\n')
   + "</pre>";