I'm updating my code to include new packages so often and I have more than 100 files.
I want to make something like this,
File : dependencies.js :
const snekfetch = require("snekfetch");
const fs = require("fs");
It's very annoying to modify every file to add just a single package.
I'm trying to require the dependencies.js using this:
require("./dependencies.js")
But I see this in my console:
ReferenceError: snekfetch is not defined
Is there any way I can succeed?
I think you are not exporting the modules in dependencies.js
dependencies.js should look like,
const snekfetch = require("snekfetch");
const fs = require("fs");
module.exports = {
"snekfetch": snekfetch,
"fs": fs
};
Then you should be able to import this file and use it like as follows,
var dependencies = require('./dependencies.js');
// dependencies.fs.readFile();
Although there are much better ways to handle your imports then just creating a simple file of dependencies. Have a look at this link.
Related
Hi,
I made an app for node.js so my app.js looks like this:
global.fs = require("fs");
global.vm = require('vm');
var includefile = function(path) {
var code = fs.readFileSync(path);
vm.runInThisContext(code, path);
}.bind(this);
includefile("variables.js");
as for variables.js I have this:
global.app = require("express")();
but when I start the app I get this error:
require is not defined at variables.js
why is it that requires loads fine if executed from app.js but not from an external file?
Thank you.
I'm a little confused, is variables.js just another source file in your project? All you should need to do is require the file in like you've done at the top. As an example for variables.js:
const Variables = {
fs: "some_value"
};
module.exports = Variables;
And for app.js
const { Variables } = require("./variables.js");
const fs = Variables.fs;
Executing console.log(fs); in app.js will print "some_value". Same can be done with functions.
If variables.js is part of your project code, you should use the answer of M. Gercz.
If it's not part of your project code and you want to get some information from it, you could use a json file:
app.js
const variables = require('variables.json');
console.log(variables.whatever);
variables.json
{ whatever: "valuable information" }
If it's not certain, that variables.json is preset, you can do a check using fs.existsSync;
Notice: As jfriend00 commented, using global is not recommended.
I'm working on my first NodeJS project. I started building modules in the classical way as I read on books and over the internet.
As the project started growing I decided to split modules in small reusable pieces. That lead me to have a lot of require at the top of the file and sometime the risk to tackle circular dependencies. Moreover, this approach, doesn't really fits with testing because I had to require all the dependencies to make tests. I asked other developers a better way to solve this problem and most of them suggested me to use dependency injection with function constructor.
Suppose I have ModuleA and ModuleB,
ModuleC requires both ModuleA and ModuleB. Instead of requiring these modules an the top of the page I should pass them as argument in a constructor function.
e.g.
module.exports = function ModuleC(moduleA, moduleB) {
//module implementation here....
function doSomething() {}
return {
doSomething
}
}
the problem with this approach, that at first looked good, is that in the main entry point of the application I have to require and instantiate all the module to pass.
const ModuleA = require("./moduleA");
const ModuleB = require("./moduleB");
const ModuleC = require("./moduleC");
const moduleA = new ModuleA();
const moduleB = new ModuleB();
const moduleC = new ModuleC(moduleA, moduleB);
moduleC.doSomething();
Now with only 3 modules I had to write 7 line of code to use a function of a module. If I had 20 modules to work with the main entry point of the application would be a nightmare.
I guess this is not the best approach and even with this method, testing is not easy.
So, I ask you to suggest/explain me the best way to achieve this simple task that I'm finding, maybe harder than it is, while starting exploring the NodeJS word. Thanks.
Code re-usability can also be achieved if you put all of your codes in a single file. Creating smaller modules is not the only solution. consider the following codes written in a file allLogic.js(let).
var allFunctions = function(){ };
var allFunctionsProto = allFunctions.prototype;
allFunctionsProto.getJSONFile = function(fileName){
var that = this; //use 'that' instead of 'this'
//code to fetch json file
};
allFunctionsProto.calculateInterest = function(price){
var that = this; //use 'that' instead of 'this'
//code to calculate interest
};
allFunctionsProto.sendResponse = function(data){
var that = this; //use 'that' instead of 'this'
//code to send response
};
//similary write all of your functions here using "allFunctionsProto.<yourFunctionName>"
module.exports = new allFunctions();
Whenever I need to get any JSON file I know that the logic to get JSON file has already been written in allLogic.js file, hence I will require this module and use that as below.
var allLogic = require('../path-to-allLogic/allLogic.js');
allLogic.getJSON();
this approach is far better than creating tons of module for each work. Of course if the module gets longer you can create new module but in that case you need to consider separation of concern otherwise the circular dependency will haunt you.
As you are using you moduleA and moduleB in moduleC, if you put all of the codes from moduleA, moduleB and moduleC in a single module as I have pointed out you can reference the functions and all of the separate functions inside that module using that and those are also available after require.
Is there any module to parse javascript using node.js . I mean we are able to add and remove html content dynamically using cheerio nodejs module.
Similarly, we want to add, remove and manipulate a javascript method/variable. Is there any module to do that. I searched but unable to get one.
Thanks in Advance !!!
I would recommend the recast module. Install it via npm install --save recast. Below is a sample program that will read in the source of a module named user.js in the current directory. It will parse the source into an AST then from the AST re-generate the original source. Modify the AST with help from estraverse before you call recast.print(ast).code.
The source (does not incorporate estraverse -- exercise for the reader):
'use strict';
var recast = require('recast');
var path = require('path');
var fs = require('fs');
var file = path.resolve(__dirname, 'user.js');
var code = fs.readFileSync(file).toString();
var ast = recast.parse(code);
var output = recast.print(ast).code;
console.log(output);
I have multiple js files, all have the same requires in the beginning like
var config = require("config");
var expect = require("chai").expect;
var commonAssertions = require('../../../utils/common_assertions.js');
var commonSteps = require('../../../utils/common_steps.js');
I am thinking about putting all of them in one file and just require this single file.
I am wondering if there is any best practice or convention on this in nodejs.
Remember that require() must always return a Javascript object, module.exports.
So if you were to extract this to a different file, that would be perfectly fine.
includes.js
exports.config = require("config");
exports.chai = require("chai").expect;
exports.commonAssertions = require('../../../utils/common_assertions.js');
exports.commonSteps = require('../../../utils/common_steps.js');
myfile.js
includes = require('./includes')
includes.expect(true).to.be.true //For example
It is not necessarily a good or bad practice. I would say that if you expect to need the exact same modules from many different files, then go for it.
I'm a bit new to NodeJS. Maybe it's just the way it works but to be sure:
My 'index.js':
var fs = require('fs');
// do something with fs here
var app = require('./app.js');
The 'app.js'
fs.readFile('/somedir/somefile.txt', 'utf8', function (err,data) {
if (err) {
return console.log(err);
}
console.log(data);
});
Then I get an error:
ReferenceError: fs is not defined
As I've read, the 'solution' to this is to 're-require' the fs-module in app.js. Now what I do understand is that the fs-module is cached (any module, but using the example) so Node will still be really quick. What I don't really get is: "If the fs-module is cached, so actually it's kinda available anyway, why do I still have to 're-require' the module?
I'll be honest; it's just to understand why.
Each file has to include references to modules
index.js
var fs = require("fs"),
other = require("./otherfile");
// you can now use `fs`
otherfile.js
var fs = require("fs");
// you can now use `fs` here
One of the best parts about this is you're not locked into naming the variable a certain way in any given file. Every file is pretty much isolated from all the other files in your lib, and that's a very good thing.
Also know that you can include just parts a module if you'd like
var read = require("fs").readFile;
read("myfile.txt", function(err, data) {
if (error) {
return throw error;
}
console.log(data);
};
Explanation:
Node.js does not encourage the use of globals; and as such, you should not try to implement things that depend on global variables.
When you call in the fs module again, it's not really "re-requiring" it so much as you're just declaring a variable that points to the cached module.
Additional example:
In this answer I go into detail about how to structure a simple app that avoids the use of globals.
Sometimes we can forget it, but it's fundamental to declare it:
var fs = require('fs');