How to import object to another file? - javascript

I'm using Node.js to build a web application.
I have two files. Server.js - where I call the server to go online etc. And the other one is a file which includes a big object with data. I imported the file with data into server.js, I get the object in postman when I set the website to be live. But I can't dive inside the object to get the data inside the object. The error I'm getting says that the variable where my data is stored is not defined.
I think the fix is to import albumsData variable into server.js, but im completely stuck and can't find how to do it. If anyone has any idea, please share.
albumsData.js
const express = require('express');
const router = express.Router();
let albumsData = {
filled with data
}
router.get('/albumData', (req, res) => {
res.send(albumsData);
});
module.exports = router;
Server.js
app.use(require('./api/albumData/unikkatilData'))
app.use((req, res) => {
res.status(404)
.send(albumsData)
});
app.listen(4000, () => {
console.log('hello worldd')
})

If you want the albumsData object then you can do it like this:
In you albumsData.js file:
const albumsData = {
// Bunch of data
}
module.exports = albumsData
Then in your server.js file:
const albumData = require('./api/albumsData') // Make sure this path points directly to the albumsData.js file

move enter code here to new file (ex utils.js)
and export it exports.albumsData = albumsData; then you can call it
with const utils = require('./utils') ; utils.albumsData

Related

how could i use require() to read a local json file by just adding the local project json file path?

This is how I managed to be able to read the json file
posts.js file
const PATH = require('/Users/jorgesisco/Dropbox/Programming_Practice/Web_Development/PWJ/Module-8/Blog/pwj-module-8-my-blog-api/exercise/data.json');
class Post {
get() {
// get posts
}
getIndividualBlog() {
// get one blog post
}
addNewPost() {
// add new post
}
readData() {
return PATH;
}
}
module.exports = Post;
Now in app.js I call the function and I am able to see the json file in postman.
// 1st import express
const express = require('express');
const app = express();
const Post = require('./api/models/posts');
const postsData = new Post();
const posts = [
{
id: '1581461442206',
title: 'This is a New Blog Post',
content: 'This is the content! ',
post_image: 'uploads/post-image-1581461442199.jpg',
added_date: '1581461442206',
},
];
// const result = posts.flatMap(Object.values);
app.get('/api/posts', (req, res) => {
res.status(200).send(postsData.readData());//here I call the function to see json file in postman
});
app.listen(3000, () => console.log('listening on http://localhost:3000'));
I think I shouldn't use the whole file path for the json file but when I just use something like ./data.json an error happen because it can't find the json file.
For accessing the files from the same dir you need to pass './'
Example: require('./data.json');
for accessing the files from one dir out from current dir '../'
Example: require('../data.json');
For accessing the files from two dir out within different folder '../../foldername/data.json'
Example: require('../../dataFolder/data.json');
The file path is referenced from the directory where you run the main code (app.js)
Move your data.json file inside the directory where your code is located. Let's say main_code/datadir. So, it looks like this now -
-- maincode
-- datadir
-- data.json
-- posts.js
-- app.js
Refer the file in posts.js code as require('./datadir/data.json')(Assuming datadir/ is in the same path/level as your app.js code)
Run app.js

Node JS mssql exporting database connection

I have hard time understanding why my code doesn't work. I am using node package mssql and want to have database pool connection initiation in separate file:
databaseConnection.js:
const sql = require("mssql/msnodesqlv8");
config = {
database: process.env.DB_NAME,
server: process.env.DB_SERVER,
driver: "msnodesqlv8",
options: {
trustedConnection: true
}
};
let pool = sql.connect(config);
module.exports = pool;
Then I have my express route file data.js
const express = require("express");
const router = express.Router();
const db = require("../configs/databaseConnection");
router.get("/dataList", async (req, res) => {
let allData = await db.request().query("select * from dataList");
console.log(allData);
res.render("dataList", { title: "Data list" });
});
module.exports = router;
However, when I start the server and go to the route I get error:
(node:13760) UnhandledPromiseRejectionWarning: TypeError: db.request is not a function
The thing is if I setup precisely as this example mssql documentation (where verything would be done in the route) it works. However, if database connection is in separate file it doesn't work.
I would appreciate any help understanding this
Regards,
Rokas
sql.connect returns a promise, so once we know that, we can either do a .then(result => ... or use await, for example:
If you want to store the db object at startup for later I'd suggest changing the line:
const db = require("../configs/databaseConnection");
to
let db = null;
require("../configs/databaseConnection").then(pool => {
db = pool;
});

How to exports many mongoose models modules in node.js

I have 2 models like this
const Db = mongoose.model('db', dbSchema);
const Beacon = mongoose.model('beacon', dbSchema2);
Now I want to export them. First I export Db and everything is fine. I can do an HTTP request with it.
module.exports = Db;
However, when I try to export ´the 2nd one outside, it stops functioning. The functions below will return a blank JSON file as a response.
module.exports = Db;
module.exports = Beacon;
This won't work either. It returns an error handler saying all my functions in the handler is not function.
module.exports = {
Db, Beacon
}
This is the function on the file I import the models.
router.get('/data/:id', function(req, res, next) {
Db.findOne({ _id: req.params.id }).then(function(db) {
res.send(db);
});
}
The return from the handler is Db.findOne is not a function.
Is there any way to export them both? Thank you.
Here is the importing on another file
const Db = require('./db.js');
const Beacon = require('.db.js');
This should work:
Exporting in one file
module.exports = { Db, Beacon };
Then, importing in another file
const { Db, Beacon } = require('path-to-db.js');
// use them
Db.doSomething();
Beacon.doSomethingElse();
Notice that this uses the ECMAS 6 Destructuring Assignment (additional info on MDN)

Facebook Messenger Bot: Understanding Export Arguments

I am trying to learn how to create a facebook Bot.
I found this amazing article on Medium which illustrates how we can create a messenger bot
In this article, The author tells us to create a verification.js. file inside controllers/verification.js. and paste the following code in it.
module.exports = (req, res) => {
const hubChallenge = req.query[‘hub.challenge’];
const hubMode = req.query[‘hub.mode’];
const verifyTokenMatches = (req.query[‘hub.verify_token’] === ‘crowdbotics’);
if (hubMode && verifyTokenMatches) {
res.status(200).send(hubChallenge);
} else {
res.status(403).end();
}
};
This, I understand to be ES6 Anonymous function which executes immediately? And since we aren't doing anything like
var express = require("express");
var app = express();
I am assuming it to be simple Vanilla JavaScript file. Now in our app.js we just import like this const verificationController = require("./controllers/verficiation.js")
Now, The question which is bothering me is that how did we passed the arguments to this module.exports = (req, res) => {
Without reading the article or knowing anything about that bot, I assume you are going to use verificationController as middleware to an express route, like this:
app.get("/", verificationController, (req, res) => {...});
This will pass req and res as parameters to the function

app.get is undefined (node.js)

In my app.js file I do the following...
var app = module.exports = express();
Then in my register.js file I am using get to render a page in the following way...
var module = require('../app');
module.app.get('/register', function (req, res) {
res.render('register.jade', { title: 'register' });
});
But I get the error that get cannot be used with app because it is undefined
If I change my get function to the following, everything works fine...
exports.register = function (req, res) {
res.render('register.jade', { title: 'register' });
};
and change my app.js to...
app.get('/register', reg.register);
... it will work.
But I want to be able to export app so I can use it in other routes. How do I properly export it?
EDIT
I just realized the proper way to to require the module is using var app = require('./app');.
The path I mentioned before is wrong.
But now I get an error cannot find module ./app, I have no idea why.
only things assigned to module.exports are visible outside of that JavaScript file. In your case that is returned value of express(). There is no module.app exported. Also, stop using module as variable name, because its one of the globals injected to the JavaScript file.
Better do something more clear and hand control to server script, which in turn will call all required setup functions on server run:
Structure:
project
|_controllers
| |_login.js
| |_register.js
|_routes.js
|_app.js
controllers/login.js :
/**
* Login user.
* #param req - express Request.
* #param res - express Response.
* #param next - calls next middleware.
*/
function login(req,res,next){
res.send("Login!");
}
// exports
module.exports = login;
controllers/register.js :
/**
* Register user.
* #param req - express Request.
* #param res - express Response.
* #param next - calls next middleware.
*/
function login(req,res,next){
res.send("Register!");
}
// exports
module.exports = register;
routes.js:
/**
* routes module.
*/
var routes = {};
/**
* Setup app routes.
* #param app - Express app instance.
*/
routes.setup = function setup(app){
app.post('/register',require('./controllers/register'));
app.post('/login',require('./controllers/login'));
}
// exports
module.exports = routes;
app.js:
var express = require('express');
var routes= require('./routes');
// init app
var app = express();
// setup routes
routes.setup(app);
// start server
app.listen(8080);
First thing I wanna say is what module.exports=... and exports.something=... do. module.exports is the object that would be import after require it. Let's say there is a file named X.js :
var A = {
name:'A'
};
module.exports = A;
Now we can import it in other file, suppose we have a file named Y.js :
var A = require('pathToX/X');
console.log(A.name);
So, in your code module.exports = express();, the object you've exported is the "express()" itself. Your should use it in other files (for example, your register.js file) in this way :
var module = require('../app');
module.get('/register', function (req, res) {
res.render('register.jade', { title: 'register' });
});
That is, when you call require('../app'), what you got is the express(). So your code module.app.get is equals to express().app.get, of cause there is no app property in express().
Besides, the module is predefined in node js, please don't use it as a variable name, you can change your register.js file to
var app = require('../app');
app.get('/register', function (req, res) {
res.render('register.jade', { title: 'register' });
});
And this is true : exports===module.exports, so you did the right way to import register in your code app.get('/register', reg.register);.
One more thing, exports={name:'A'} is NOT equals to module.exports={name:'A'}, that is pretty straightforward, exports is just a variable link to module.exports, change the exports link itself won't change module.exports.
In your app.js, try something more like:
module.exports = {
app: express()
}
Then when you do var module = require('./app'), module will contain an object which has an app property.
Note that I don't know what express() does, but I am assuming it is returning an object that has a get() function on it.
try this
//app.js
var express = require('express');
var app = module.exports = express();
//register.js
var module = require('./app.js');
//var http = require('http');
//var server = http.createServer(module);
module.get('/register', function(req,res,next) {
// body...
console.log("register");
});
//server.listen(1338);

Categories