0

I am using node.js. I would written several javascript functions to be shared across several files. I want to put these functions into a single file tools.js. Based on the answer in

In Node.js, how do I "include" functions from my other files?

the functions need to be declared in this format (function expressions);

// tools.js
// ========
module.exports = {
  foo: function () {
    // whatever
  },
  bar: function () {
    // whatever
  }
};

However, the functions I have written are of this format;

function foo(a, b, c)
{
    //do whatever
}

I have several such functions. It is a chore to re-declare all of them in tools.js as function expressions. Is it possible to have tools.js use functions declared in my way?

Community
  • 1
  • 1
guagay_wk
  • 26,337
  • 54
  • 186
  • 295

2 Answers2

1

Yes, but it's even more work.

If you are on a kind of Unix and your format is exactly as described here you can use

sed -e 's/^\(function\)\([ ]\+\)\([a-zA-Z0-9]\+\)/\3: \1/g;s/^\}/\},/g'

to exchange the function declaration and put a comma after the last bracket. Also after the very last bracket but I don't think it's too much work to get rid of it by hand.

But as you are already playing with node you might use something in the line of the following (beware: works in-place!):

var fs = require('fs')
fs.readFile(YOUR_FILE, 'utf8', function (err,data) {
  var result;
  // checks&balances omitted
  result = data.replace(/(function)([ ]+)([a-zA-Z-0-9]+)/g,"$3: $1");
  result = data.replace(/^}/g,"},");
  fs.writeFile(YOUR_FILE, result, 'utf8', function (err) {
     // checks&balances omitted
  });
});

(shouldn't it be utf-16?)

deamentiaemundi
  • 5,502
  • 2
  • 12
  • 20
0

Thanks to help from wonderful experts on hand, the simple answer to my own question is as follows;

// tools.js
// ========
module.exports = {
  foo: foo,
  bar: bar,
};
guagay_wk
  • 26,337
  • 54
  • 186
  • 295