user274065 user274065 - 12 days ago 5
Javascript Question

How to properly import using the CommonJS way

I am confused on how to import a function in a file called util.js that simply reverses a string

function reverseString(str) {
var reversed = " ";
for (var i = str.length - 1; i >= 0; i--) {
reversed += str[i];
}
return reversed;
}
module.exports.reverseString = reverseString;


I want to access that in a different file, this one called server.js

This is what I have so far.

var util = require('./util');

util.reverseString();




var reversed = reverseString(req.body);
res.send(reversed);
} else {
res.status(400).end()
}
});


I am using postman to check the node modules, but when I run it I get

TypeError: Cannot read property 'length' of undefined


I know the reverse code works, because I tested it earlier, so I assume my import is incorrect. But any help figuring this out would be great.

Answer

reverseString function is expecting an argument of type string(may be array also) and this same function you are iterating over the argument.

But while calling this function you are not passing any parameter, so str argument is setting to undefined.

undefined do not have any length property so it is thowing this error