Does require and module.exports in NodeJS could be used to obtain all functions in all JavaScript files residing in a directory rather than in a single JavaScript file? If so HOW? Could anyone please explain it with an example ?
If require is given the directory path, it'll look for an index.js file in that directory. So putting your module specific js files in a directory, creating an index.js file & finally require that directory in your working js file should do. Hope example below helps....
Example:
file: modules/moduleA.js
function A (msg) {
this.message = msg;
}
module.exports = A;
file: modules/moduleB.js
function B (num) {
this.number = num;
}
module.exports = B;
file: modules/index.js
module.exports.A = require("./moduleA.js");
module.exports.B = require("./moduleB.js");
file: test.js
var modules = require("./modules");
var myMsg = new modules.A("hello");
var myNum = new modules.B("000");
console.log(myMsg.message);
console.log(myNum.number);
By using require
you required the module in that file and you can use the all function of that prototype (single file ) not a complete directory.
e.g
function admin(admin_id)
{
//console.log(parent_id);
this.admin_id = admin_id;
}
//default constructor
function admin()
{
admin_id = null;
self =this;
}
//destructor
~function admin(){
this.admin_id = null;
console.log('admin obj destroyed!');
}
//exporting this class to access anywhere through data encapstulation
module.exports = admin;
//class methods
admin.prototype = {
help:function(params){
console.log('hi');
}
},
you can require this module and can use the function help
and by this method u can require all file (modules) in single file
Wiki: "Node.js is an open-source, cross-platform runtime environment for developing server-side Web applications.
Although Node.js is not a JavaScript framework, many of its basic modules are written in JavaScript, and developers can write new modules in JavaScript.
The runtime environment interprets JavaScript using Google's V8 JavaScript engine."
Nodejs example:
You have Afile.js
var Afile = function()
{
};
Afile.prototype.functionA = function()
{
return 'this is Afile';
}
module.exports = Afile;
And Bfile.js
var Bfile = function()
{
};
Bfile.prototype.functionB = function()
{
return 'this is Bfile';
}
module.exports = Bfile;
The Test.js file require Afile.js and Bfile.js
var Afile = require(__dirname + '/Afile.js');
var Bfile = require(__dirname + '/Bfile.js');
var Test = function()
{
};
Test.prototype.start = function()
{
var Afile = new Afile();
var Bfile = new Bfile();
Afile.functionA();
Bfile.functionB();
}
var test = Test;
test.start();
Related
I have some .java files inside a directory, I want to read those files and get some values inside each of them. I'm not sure on how to proceed. how can I do this using fs module and some other npm modules in node js.
Below is my current code
const path = require('path');
var fs = require('fs');
module.exports={
readTS: function () {
var CWD = path.join(__dirname, '../');
var folder = path.basename(CWD).toLowerCase();
var TSJavaPath = path.join(__dirname, '../src/main/java/com/'+folder+'/');
var files = fs.readdirSync(TSJavaPath).filter(fn => fn.startsWith('TS'));
console.log(files);
for(i=0;i<files;i++){
//Read and get data
}
}
};
You could compile your .java files and read them using leonardosnt/java-class-tools.
You have HelloWorld.java -
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World");
}
}
Then compile -
javac HelloWorld.java
Then write a quick index.js -
const { JavaClassFileReader } = require('java-class-tools');
const reader = new JavaClassFileReader();
const classFile = reader.read('./HelloWorld.class');
classFile.methods.forEach(md => {
/**
* Method name in constant-pool.
*
* Points to a CONSTANT_Utf8_info structure: https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-4.html#jvms-4.4.7
*/
const nameInConstantPool = classFile.constant_pool[md.name_index];
// To string (hacky)
const name = String.fromCharCode.apply(null, nameInConstantPool.bytes);
console.log(name);
});
Which outputs the following -
node index.js
<init>
main
I have this 2 files:
APP.js:
const Request = require('request');
const YVideo = require('./classes/YVideo');
const yvideo = new YTVideo();
YVideo.js:
class YVideo {
constructor(uuid){
this.uuid = uuid;
this.url = 'https://example.com/get_video_info?uuid=';
Request.get(this.url+this.uuid, function(err, resp, body){
this.data = body.split('&');
});
console.log(this.data);
}
}
exports = module.exports = YTVideo;
The code runs until "Request.get(...)". Console shows this error:
"ReferenceError: Request is not defined".
Now, I'm new with Node.js, so what I ask is: Should I require the same module each time for all .js where I use it or there's a way to require it once for entire app?
Question: Should I require the same module each time for all .js where I use it
or there's a way to require it once for entire app?
require locally loads each module, so you will have to use require in every .js file you need the module.
From https://www.w3resource.com/node.js/nodejs-global-object.php
The require() function is a built-in function, and used to include
other modules that exist in separate files, a string specifying the
module to load. It accepts a single argument. It is not global but
rather local to each module.
It has to be required in all the files where you need it. So add it in YVideo file where it is needed.
const Request = require('request');
class YVideo {
constructor(uuid){
this.uuid = uuid;
this.url = 'https://example.com/get_video_info?uuid=';
Request.get(this.url+this.uuid, function(err, resp, body){
this.data = body.split('&');
});
console.log(this.data);
}
}
exports = module.exports = YTVideo;
I want to pass my logServiceClient object to all other modules included in server.js file. When I run below code it prints empty object;
logServiceClient{}
Is there any way to pass logServiceClient to all other included modules?
server.js file;
....
const logger = new Logger({
level: new CLevel('warn'),
ordered
})
var logServiceClient = require('./app/logServiceClient')(logger)
var userHandler = require('./app/userHandler')(logServiceClient)
userHandler file;
module.exports = function(logServiceClient){
console.log('logServiceClient' + JSON.stringify(logServiceClient))
}
There a many ways to inject without pulling in the logger from your other modules.
Use a factory to indirectly create and initialize your objects/modules
function factoryCreateModule() {
var client = require('client')
client.$logger = require('logger')
}
function factoryRequireModule(module) {
var client = require(module)
client.$logger = require('logger')
}
var client = factoryCreateModule()
client.logger.log('hello')
var client2 = factoryRequireModule('client')
client2.logger.log('hello')
Add your logger to all objects using prototype
Of course you can narrow down the target object...
var logger = {
log(message) {
console.log(message)
},
warn(message) {
console.log('!!! ' + message)
}
}
Object.prototype.$logger = logger
var x = 12;
x.$logger.log('I am a number')
var str = "Hello"
str.$logger.warn('WARNING FROM STRING')
Make your logger global
global is the 'window' in the module system.
// just for snippit to run
window.global = {}
var logger = {
log(message) {
console.log(message)
}
}
// main module
global.$logger = logger
// client module
global.$logger.log('hello world')
Pass the logger into the constructor or init method
var logger = require('logger')
var client = require('client')(logger)
var client2 = require('client2')({logger})
var client3 = require('client3')
client3.init(logger)
// file1.js
var foo = "bar";
exports.foo = foo;
//file2.js
var myModule = require('./file1');
var foo = myModule.foo;
I am trying to update a json value from a grunt task i have.
This bit of code works
var number = 123456;
var setRandomNumber = function() {
var fs = require('fs');
var fs = require('fs-extra');
var filename = 'my.json';
var config = JSON.parse(fs.readFileSync(filename), 'utf8');
console.log(config.randomNumber);
};
setRandomNumber();
What I want to do is update config.randomNumber to be the value of number.
Can anyone point me in the right direction?
Ta
here is an example of updating the version of the package.json file using a grunt task. (from 0.0.0 to 1.0.0 to 2.0.0);
module.exports = function(grunt) {
grunt.registerTask('version', function(key, value) {
var projectFile = "package.json";
if (!grunt.file.exists(projectFile)) {
grunt.log.error("file " + projectFile + " not found");
return true; //return false to abort the execution
}
var project = grunt.file.readJSON(projectFile), //get file as json object
currentVersion = project["version"].split('.');
currentVersion[lastIndex] = Number(currentVersion[0]) + 1
currentVersion = currentVersion.join('.');
project["version"] = currentVersion;
grunt.file.write(projectFile, JSON.stringify(project, null, 2));
});
}
now you can call the task version to increment the file by writing
grunt version
or you can add it to your production process, for example:
module.exports = function(grunt) {
grunt.registerTask('buildProd', [
'version'
]);
};
I am using node.js (v4.2.2) with express (4.13.1). I am trying to import my custom module functions to another module. Application is created with express, and only thing added to app.js is require for my route var tests = require('./routes/tests'); and app.use for that route app.use('/tests', tests);
My two custom files (modules) are (path is relative to project root):
./model/test.js
./routes/tests.js
Here is ./model/test.js:
var id;
var testNumber1;
var testNumber2;
function Test(id, testNumber1, testNumber2) {
this.id = id;
this.testNumber1 = testNumber1;
this.testNumber2 = testNumber2;
};
exports.reset = function() {
this.testNumber1 = 0;
this.testNumber2 = 0;
};
module.exports = Test;
And here is ./routes/tests.js:
var express = require('express');
var Red = require('../model/test.js');
var router = express.Router();
/*create new test :id*/
router.post('/:id', function(req, res, next) {
var myNewTest = new Red(req.params.id, 0, 0)
myNewTest.testNumber2 += 1;
myNewTest.reset();
res.send('id: ' + myNewTest.id +
' testNumber2: ' + myNewTest.testNumber2);
});
module.exports = router;
When I try to execute curl -X POST http://localhost:3000/tests/1 i get error TypeError: myNewTest.reset is not a function. I am having trouble understanding how to export functions correctly. If I understand this api reference correctly, to expose constructor of module, i have to use module.exports = Test;, but that doesn't expose reset function. So, to expose it I have declared it like exports.reset = function() {...}, but obviously, that doesn't work, at least not in my case.
Through some other answers I have also seen function being declared normally function reset() {...}, and exposed like exports.reset = reset;, which gives me the same error.
How do I expose reset function properly?
You should add it to the prototype, at the moment it's just a static method in your module, not attached to the Test constructor.
function Test(id, testNumber1, testNumber2) {
this.id = id;
this.testNumber1 = testNumber1;
this.testNumber2 = testNumber2;
};
Test.prototype.reset = function() {
this.testNumber1 = 0;
this.testNumber2 = 0;
};
module.exports = Test;