Currently I am working on a personal project and am running into a problem understanding the functionality of module.exports within my app...
My app structure looks like this:
app
├── common
│ ├── cmd
│ │ ├── run-cmd.js
├── routes
│ ├── system
│ │ ├── temp.js
I am hoping to achieve a way to store reusable functions in a separate location in my app (in this example run-cmd.js
) and have them easily accessible throughout the rest of my app (temp.js
) without having to specifically reference the file path (example: require(../../folder/folder/file)
Here is run-cmd.js
:
const { spawn } = require("child_process");
module.exports.runCmd = (cmd, callback) => {
var command = spawn(cmd, [], {shell:true});
const REGEX_LINE_BREAK = /(\r\n|\n|\r)/gm;
var result = '';
command.stdout.on('data', function(data) {
console.log(data.toString())
result += data.toString().replace(REGEX_LINE_BREAK, "");
});
command.on('close', (code) => {
console.log("code: " + code)
return callback(result);
});
}
Here is temp.js
:
var express = require('express'),
router = express.Router(),
runCmd = require('../../common/cmd/run-cmd');
// Add a binding to handle '/temp'
router
.get('/temp', (req, res) => {
runCmd('vcgencmd measure_temp', function(result) {
console.log("Result we are prepping to send: " + result);
res.json({result: result});
});
});
module.exports = router;
I feel like the require()
example above defeats the purpose of the flexibility of using module.exports... where doing something like require(./run-cmd)
or even require(from-root/path/run-cmd)
would be much better to reference in other locations throughout my app. Additionally, in this current example I get an error saying TypeError: runCmd is not a function
.
Can anyone help clear some of my confusion with using module.exports
and tell me where I am going wrong?