I currently have a massive node JS file (3100+ line of code) and I am trying to split it up into multiple files. I have taken one of the functions and a bunch of firebase database references and put them into their own file inside their own class. For some reason the Firebase references give me an error no matter what even when the syntax seams to be okay:
/.../lib/context.js:13
static database = firebase.database()
^
SyntaxError: Unexpected token =
Here is my code for importing the file
// index.js
'use strict'
var ... = ...()
...
var util = require('util')
var fs = require('fs')
var http = require('http')
var firebase = require('firebase')
var Context = require('./lib/context.js')
and here is my code of the imported file:
'use strict'
var util = require('util')
var firebase = require('firebase')
exports.Context = class
{
constructor()
{
}
static database = firebase.database()
static homeworkRef = database.ref("/homework")
static usersRef = database.ref("/users")
static announcementsRef = database.ref("/announcements")
static votingRef = database.ref("/voting")
static feedbackRef = database.ref("/feedback")
static peerRef = database.ref("/peer_review")
Am I requiring the file correctly? Why does this error keep happening? It worked fine while it was in one file.
Related
I am trying to use host the following js file using nodejs as my first time. The following is the beginning of code to it. I had to use JSDOM since I was trying to use the buttons from the blog.html file in here. The file 'index.html' is present in the folder public and when I run it on terminal, I see the message 'hosting' but it says 'cannot GET /'. Here is my code:
var request = require('request');
const express = require('express');
const app =express();
app.listen(3000, ()=>console.log('hosting'));
app.use(express.static('public' ));
app.get('./blog.html', function(request, response) {
response.sendFile('blog.html');
});
var jsdom = require('jsdom');
const { JSDOM } = jsdom;
const { document } = (new JSDOM('blog.html')).window;
global.document = document;
const postBtn1 = document.getElementById("post-btn1");
const postBtn2 = document.getElementById("post-btn2");
const postBtn3 = document.getElementById("post-btn3");
I have a file called data.js for keeping data as memory database.
var express = require('express');
var app = express();
var aList;
var bList;
var cList;
module.exports = app;
And I want to initialise data when I start the server. So, I implemented init() in app.js
...
var data = require('./data'); // data.js is located in the same folder.
app.set(...);
app.use(...);
...
init();
...
});
fun init(){
console.log("Hello!");
aList = getDumpDataList(10); // I also tried with 'data.aList = getDumpDataList(10);' but didn't work.
console.log(JSON.stringify(aList));
}
fun getDumpDataList(n){
var list;
... // for loop to generate random elements.
return list;
}
module.exports = app;
When I printed with console.log(), Hello! is printed but aList isn't printed but undefined
And I also want to use the data in routers under routes folder.
So, what I did is.
...
var data = require('./data');
route.get("/...", function(req, res, next){
console.log(JSON.stringify(aList));
...
});
But it is also undefined.
I am just making simple test server that initialise data whenever I re-run.
How can I share variables between the js files?
You do not export those vars:
const express = require('express');
const app = express();
let aList;
let bList;
let cList;
module.exports.app = app;
module.exports.aList = aList;
module.exports.bList = bList;
module.exports.cList = cList;
...but i would not put express in data.js, rather put it in app.js.
I would also initialize those vars with initial values in data.js, if the initial data does not depend on something else.
Last but not least: Do not use var anymore, use let and const instead. It is supported since Node 6+ (https://node.green/). I replaced it in the code.
Is there a way to get the version of an external dependency in JS code, without hardcoding it?
If you wanted to get the value of express you could do something like the following. You are looping over each folder in the node modules and adding the name and the version to an object.
const fs = require('fs');
const dirs = fs.readdirSync('node_modules');
const packages = {};
dirs.forEach(function(dir) {
const file = 'node_modules/' + dir + '/package.json';
const json = require(file);
const name = json.name;
const version = json.version;
packages[name] = name;
packages[version] = version;
});
console.log(packages['react-native']); // will log the version
i want to access a model name userRegistration in my custom js file but every time its showing undefined and shows this error
TypeError: Cannot call method 'findOne' of undefined
please Check code
var loopback = require('loopback');
var app = loopback();
var nodemailer = require("nodemailer");
var smtpTransport = require("nodemailer-smtp-transport");
var path=require('path');
var fs=require('fs');
var Handlebars = require('handlebars');
exports.mailToUser=function(req,res,next){
var userNotification = app.models.UserNotification;
var userregister = app.models.UserRegistration;
userregister.findOne({where:{email:email}},function(err,userobj){
if(err){
next()
}
})
}
Thanks
You shouldn't use var app = loopback();
If you want to access to app you can require your server.js or some other ways existed. The simple one is requiring server
My export code
//export.js
var express = require('express'),
fs = require('fs'),
request = require('request'),
cheerio = require('cheerio'),
app = express();
var episode = [],
title = [],
synopsis = [],
reviews = [],
date = [];
exports.showGrab = function(url,response){
request(url,response, function(error, response, html){
var $ = cheerio.load(html),
shows = {bitten:['http://www.tv.com/shows/bitten-2013/episodes/']};
$('.no_toggle._clearfix').eq(1).filter(function(){
var data = $(this);
episode = data.children().first().children().last().text();
exports.episode = episode;
})
})
}
console.log(episode); // => defined as [] not the value given in the function
//import.js
var express = require('express'),
fs = require('fs'),
request = require('request'),
cheerio = require('cheerio'),
app = express(),
server = require('./export');
console.log(server.episode);
server.showGrab('http://www.tv.com/shows/bitten-2013/episodes/');
within the import script using the function server.showGrab works fine but I need access to the variables within the show grab function in my import script. I believe this problem boils down to a scope issue, if I export variables outside a function they work fine but I was under the impression that declaring variables the way I have done would make them global. How can I run this function in the import script whilst still passing it a url and getting back episode to work with?
#Pointy you were right the import script was calling the value before it was defined
//import.js
if (server.episode === undefined){
var test = setInterval(function(){
if (server.episode != undefined){
clearInterval(test);
}
console.log(server.episode);
}, 1000);
}
this does the trick, for some reason using else instead of wrapping an if in an if does not work.