importing modules from other folders nodejs - javascript

This is kind of a silly question, but I want to be able to write code in different files, and then import the code and use it all, like have it written in different files and it all work together.
like this:
routes
login.js
register.js
views
index.ejs
login.ejs
register.ejs
app.js
so if I create a function inside register.js, how do I say, hey, call that function in login.js now, and have it work? do I have to import the files all in app.js? I have only done small projects where this hasn't been necessary, but now I need to :)
Thanks for the help

You can use module.exports object to make your function accessible in another file.
let's say you have defined 2 functions in register.js as follows
const registerfunction1=()=>{
console.log("console registerfunction1")
}
const registerfunction2=()=>{
console.log("console registerfunction2")
}
module.exports={
registerfunction1,
registerfunction2
}
Now you can call these functions any file by using the node require as follows.
for example
//importing register module
const register=require('./register');
const loginFunction=()=>{
// calling function defined in register
register.registerfunction1();
console.log("loginFunction");
};
//calling function
loginFunction();

Related

laravel 8 include certain javascrip file into other js file

I have two files, one is my main js file called app.js and I have a file where I store all my js functions, called functions.js. As you can see on the image below.
But I want to include the functions.js file into the app.js file. So I googled on how to do it and this is what people said:
But my npm run dev says the file doesn't exist. But the path is correct. What am I doing wrong here, is there a other way to do it?
You can simply just create the file wherever you want to create it, and then export some properties or methods, and then import them in your app.js file, or in whatever file you need. Something like this :
//new_file.js
export const jokes = function() {
return ['funny', 'not really funny', 'boring']
}
export const heading = 'some global heading to be reused.'
And in your app.js file :
import { jokes, heading } from 'new_file.js'//specify actual path here .
console.log(jokes) // ['funny', 'not really funny', 'boring']
console.log(heading)//some global heading to be reused.
This tutorial might be helpful too .
http://www.2ality.com/2014/09/es6-modules-final.html

Exporting one set of functions from multiple files

I've just finished writing a big quickbooks wrapper in JavaScript with a lot of parts in different files, e.g. a file for tax, a file for accounts, a file for auth, etc. I'd like to make it so that developers using this wrapper will only have to do one import that will contain all the functions I've written.
Hierarchy is something like this:
QbTax.js
QbAccounts.js
QbAuth.js
I'd like to have another file, or a way that a developer using this wrapper would only have to import one thing, then be able to call all functions from the above files from that one import.
Something like this:
import * as qb from './unifiedQbFile.js';
qb.thisIsATaxFunc();
qb.thisIsAnAccountsFunc();
qb.thisIsAnAuthFunc();
What is the best way to approach this?
The only idea I have at the moment is to write prototypes in a file (unifiedQbFile.js for instance) and export those. I'd import all the functions from my other files in that unified file then call them in my new prototypes. That seems messy though.
you can have one index.js file that exports all files then you can import that index.js file. I would personally go with this method.
// index.js
export { qbTaxFunc } from 'QBTax';
export { qbAccountsFunc } from 'QbAccounts';
export { qbAuthFunc } from 'QbAuth';
Now in some other script to import it you can do.
import qb from 'path-to-index.js';
// All functions should now be available
qb.qbTaxFunc();
qb.qbAccountsFunc();
qb.qbAuthFunc();

How does the JavaScript Import work under the hood?

How does the import statement actually work in JavaScript? I read the documentation and it says that it places exported code within the scope of the file. Does that mean that the code is copied over into the file where I type import?
For example - in library.js I have:
export {export function getUsefulContents(url, callback) {
getJSON(url, data => callback(JSON.parse(data)));
}
In main.js I have:
import { getUsefulContents} from 'library.js';
getUsefulContents('http://www.example.com',
data => { doSomethingUseful(data); });
This allows me to call getUsefulContents() in main.js. My question is, does main.js now have the contents that I exported from library.js?
Is using import the same as just having physically defined getUsefulContents() in main.js?
function getUsefulContents(url, callback) {
getJSON(url, data => callback(JSON.parse(data)));
}
getUsefulContents('http://www.example.com',
data => { doSomethingUseful(data); });
The main reason why I ask is because I want to know if using import will have an effect on main.js file size? Or is something else going on under the hood?
Thank you!
Depends on how you are using main.js. If you run it through a bundler, then the bundler will probably include library.js into main.js to pack it up into one file. In that case, the only advantage would be maintainability and ease of development because you are focused on the file you are working on. If you are simply running the import statement and deploying your application, the import statement won't affect the file size of main.js.
It just namespacing it within the file that you are importing it to so
any code from useful-library.js is included in the file, I visualize it this way
import { usefulCodeFromLibrary } from './useful-library.js';
((usefulCodeFromLibrary)=>{
// My excellent code
// Imported code doing it's job
usefulCodeFromLibrary.someHelperFunction()
}()

unusual unexpected token in webpack

I have a file call scripts.js and it merely do var main = require('./main');
and my main.js is at the same level, it has
module.exports = {
console.log("hello");
}
I do webpack in my terminal I got unexpected token?
You can not include function executions into a javascript object (you are exporting an object), you need to export a function to achieve this
module.exports = function() {
console.log("hello");
}
And from your file where you require the export
var main = require('./main')(); // Add () to execute the function that you obtained
UPDATE:
You are executing console.log() in your main.js file, think that you can simply require some script without exporting nothing, and that file should be executed. For example you can put console.log("hello") without all the module.exports thing and the code should be executed, but when you check the value of your main variable (in the file where you do the require), you probably would not find anything useful.
You can also export a function(like in the code i send before) and then execute that function later, there's many ways to aproach this, I recommend you to google a bit about how module export works and how can you use it
You can check more about module.exports here https://www.sitepoint.com/understanding-module-exports-exports-node-js/, you are using it for the browser, but this examples for node should be usefull anyways

How can I do my routing without having one long file of all the routes in nodejs?

Using this link as a reference https://github.com/visionmedia/express/tree/master/examples/route-separation to what "could be done"
I AM NOT USING EXPRESS. I AM USING THEM AS AN EXAMPLE.
I want to do something like this but "simpler" ...
How can I get away from declaring all my routes in one long, complex list all in one file? Can I define them by passing a router into my modules, and then including all the code in one directory ... ok, I'll suffer having one long document that only does "require" includes, like an index.js, for this one ~ at least that one my build scripts can rebuild for me, but preferably not in my primary file for every single route that I may add.
So for instance, they use this code:
// General
app.get('/', site.index);
// User
app.all('/users', user.list);
app.all('/user/:id/:op?', user.load);
app.get('/user/:id', user.view);
app.get('/user/:id/view', user.view);
app.get('/user/:id/edit', user.edit);
app.put('/user/:id/edit', user.update);
// Posts
app.get('/posts', post.list);
I want to avoid making a list like that in my app.js. I want instead to have each file know what the routes are for that file.
Here's what I'm wanting to do: (please don't critique the code, I'm making it very simple so I make sure that I am illustrating my code the way I want to do it)
//app.js
var router = require('./myRouter.js')
var includes = require('./routes/*.js').register(router)
// do some stuff here with an https server and start the server here
and
//./routes/user.js
var myRouter;
exports.register(router){
myRouter = router;
}
router.addRoute(/* here I do the magic associated with this route */)
Can I do it just that simply? What am I missing here?
I haven't written this code because I'm just ever so certain that I'm going about this the wrong way.
And if I am going to have to use something like an index.js in the /routes/ folder, can I use that same concept that I demonstrated I would like to use in my code of .register(router) appended so I can pass that information down recursively? Would that work?
I use an index.js file for this and use require("routes") which is a folder.
// app.js
route = require("./routes"),
...
route(app);
// routes/index.js
var index = require("./index-route"),
about = require("./about-route"),
posts = require("./posts-route");
module.exports = function(app) {
index(app);
about(app);
posts(app);
};
This works because if you require a folder it will load index.js by default.
If you have a lot of routes you might want to load them based on convention
var routes = [];
// read all files
fs.readdir("./", function(files) {
files.forEach(function(val) {
// require all non-index.js files.
if (val !== "index.js") {
routes.push(require(val));
}
});
});
module.exports = function(app) {
// for each route you required call it with app.
routes.forEach(val.bind(null, app));
}
This would load all .js files that are not "index.js", so any file in your /routes/ folder would be loaded and run when you route them.
Your solution looks vaguely like you wish to use the Visitor Patern, in which case I suggest you make ./roots/ require-able (see this question) and in index.js you include all the files you wish (as local's) and export a register module which calls the register module on each of the required files.
Or you could copy the code from the above answer directly into your main file.

Categories

Resources