Module.exports not finding function - node.js

So I am creating a basic user login system (this is one of my first nodejs projects) and I am wanting to redirect the user to the 'dashboard' page with a successful login.
First of all I am not sure this is the best way to do the redirecting so I am open to suggestions.
The problem I am having is after calling the function and the user logs in I want to call this function:
var loginResponse = () =>{
io.emit('loginResponse');
}
This is in the server.js file (the main server file) and I am exporting it like so
module.exports = {
loginResponse : loginResponse
};
I am then after all the validation, calling db etc. is done wanting to call it in the login.js file as shown:
var createUserSession = (userSessionObj) =>{
session.user = userSessionObj;
serverMain.loginResponse();
};
I am requiring the file server file like so:
const serverMain = require('../server');
However, I am getting the following error on execute:
(node:35012) UnhandledPromiseRejectionWarning: TypeError: serverMain.loginResponse is not a function
at createUserSession (/Users/chrisholder/Documents/Programming/RandomPrograms/registerlogin/server/registrationlogin/login.js:83:14)
at hashing.comparePassword.then (/Users/chrisholder/Documents/Programming/RandomPrograms/registerlogin/server/registrationlogin/login.js:73:7)
at <anonymous>
(node:35012) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:35012) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
I have tried using the 'path' module as another way to requiring the server.js file however, it has not worked.
Thanks for your help!

Related

fs.readFileSync(filePath, function read(err, data) {} does not work even tho the targeted file is in the correct location

Here's my relevant code:
1)
let pickenFile = randomItemFormatted.source_filenametxt;
let filePath = `textFiles/${pickenFile}`;
This happens after an axios.get() that returns the name of the file.
The problem does not come from the name of the file itself.
2)
fs.readFileSync(filePath, function read(err, data) {
if(err){
console.log(err);
runTheBot();
}else{
// I should be able to access the data here :(
console.log(data);
tokenizer = new natural.SentenceTokenizer();
let textToTokenize = tokenizer.tokenize(data.toString('utf8').replace(/\0/g, ''));
dataObj.randomItemFormatted = randomItemFormatted;
dataObj.stringsArray = textToTokenize;
return returnSpecificString(dataObj);
}
});
})}
When I pass the filePath to the fs.readFileSync(), the code does not pass the error block. I'm adding the full error response here:
(node:9500) UnhandledPromiseRejectionWarning: Error: ENOENT: no such file or directory, open 'textFiles/1884_Ford__Bradstreet.txt'
at Object.openSync (fs.js:447:3)
at Object.readFileSync (fs.js:349:35)
at /Users/cyrus/Documents/Code/01. Code/franklin-ford-bot/server_side/server.js:74:9
at processTicksAndRejections (internal/process/task_queues.js:85:5)
(node:9500) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:9500) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Here's also my project's architecture where the targeted .txt files are hosted.I start the server with the node server_side/server.js.
It was working previously and nothing changed in the code since when it was working.
fs.readFileSync() does not take a callback. Your code is trying to use the fs.readFile() interface with fs.readFileSync(). See the doc.
Errors from fs.readFileSync() will be thrown as exceptions so you need try/catch around it to catch errors.
The general structure for using fs.readFileSync() in the code you show would look like this:
try {
let data = fs.readFileSync(filePath);
// I should be able to access the data here :(
console.log(data);
tokenizer = new natural.SentenceTokenizer();
let textToTokenize = tokenizer.tokenize(data.toString('utf8').replace(/\0/g, ''));
dataObj.randomItemFormatted = randomItemFormatted;
dataObj.stringsArray = textToTokenize;
return returnSpecificString(dataObj);
} catch(e) {
console.log(e);
runTheBot();
return something;
}
Now, as for the ENOENT error, that is a separate problem to fix. What I would suggest is that you do this:
const path = require('path');
let filePath = `textFiles/${pickenFile}`
console.log(path.resolve(filePath));
This will show you the full path for the file you were attempting to use. It seems likely that either the full path is not exactly what you expected it to be or there is a file permission issue preventing you from accessing it.
If the textFiles subdirectory you are trying to access is below the module directory where this code is running from, then you may want to use __dirname to reference it like this:
const path = require('path');
let filePath = path.join(__dirname, "textFiles", pickenFile);

Parse Sever with custom Express app Master Key Permission Denied

We have a custom express app that loads in the node.js parse server sdk. When we try to use a function call that requires the master key we keep getting errors for permission denied.
at /Users/gateway/Documents/lm/Website/lm-node/node_modules/parse/lib/node/RESTController.js:324:19
at processTicksAndRejections (internal/process/task_queues.js:86:5)
(node:61092) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 4)
(node:61092) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
we initiate our parse server like this..
Parse.initialize(process.env.PARSE_STAGING_APP_ID, null, process.env.PARSE_STAGING_MASTER_KEY);
//Parse.Cloud.useMasterKey();
Parse.serverURL = process.env.PARSE_STAGING_SERVER_URL;
Parse.User.enableUnsafeCurrentUser();
module.exports = Parse
async function channelStatus(orgId) {
const Status = Parse.Object.extend("Status");
const query = new Parse.Query(Status);
query.equalTo("orgID", orgId);
try {
const results = await query.first({useMasterKey: true});
if(results) {
// do some stuff
results.save();
} else {
const StatusNew = Parse.Object.extend("Status");
const statusNew = new StatusNew();
// do some stuff
statusNew.save()
}
} catch (error) {
throw error;
}
}
if we enable Parse.Cloud.useMasterKey(); it works but this can be bad because it works for every function.. we want to make sure we are using masterKey on certain functions..
thoughts?
full error in visual studio.
(node:35145) UnhandledPromiseRejectionWarning: Error: Permission denied for action get on class Status.
at /Users/gateway/Documents/lmx/WebSite/lmx/node_modules/parse/lib/node/RESTController.js:324:19
at process._tickCallback (internal/process/next_tick.js:68:7)
(node:35145) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 4)
(node:35145) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
GET /test - - ms - -
Logs
Jul 29 13:08:29 lmx-stage app/web.1: error: Error generating response. ParseError {
Jul 29 13:08:29 lmx-stage app/web.1: code: 119,
Jul 29 13:08:29 lmx-stage app/web.1: message: 'Permission denied for action get on class Status.' } code=119, message=Permission denied for action get on class Status.
Jul 29 13:08:29 lmx-stage app/web.1: error: Permission denied for action get on class Status. code=119, message=Permission denied for action get on class Status.

With Node.JS Readline: "TypeError: rl is not async iterable"

When I run the very code listed in the readline example
async function processLineByLine() {
const fileStream = fs.createReadStream('input.txt');
const rl = readline.createInterface({
input: fileStream,
crlfDelay: Infinity
});
// Note: we use the crlfDelay option to recognize all instances of CR LF
// ('\r\n') in input.txt as a single line break.
for await (const line of rl) {
// Each line in input.txt will be successively available here as `line`.
console.log(`Line from file: ${line}`);
}
}
processLineByLine();
I get the following error:
(node:27485) UnhandledPromiseRejectionWarning: TypeError: rl is not async iterable
at processLineByLine (file:///home/ecarroll/code/toponym-esque/process.mjs:16:28)
at file:///home/ecarroll/code/toponym-esque/process.mjs:22:1
at ModuleJob.run (internal/modules/esm/module_job.js:95:12)
(node:27485) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:27485) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
The changes to readline are a feature in Node v11.4.0.
readline: The readline module now supports async iterators. https://github.com/nodejs/node/pull/23916
You'll have to upgrade if you're running a prior version.

NodeJs Require module returns an empty object

I'm using NodeJS 8 LTS.
I have 3 js scripts where:
// main.js
const dom = require ('./Domains/Domains');
const factory = require ('./Domains/Factory');
(async () => {
const Domain = await factory.foo(); // <=== Error
})();
// Domains.js
class Domains {
constructor (options = {}) {
....
}
}
module.exports = Domains;
// Factory.js
const Domains = require('./Domains');
module.exports = {
foo: async () =>{
.... async stuff ...
return new Domains();
}
};
when I run main.js I get
(node:1816) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: Domains is not a constructor
warning.js:18
(node:1816) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Debugging, I found that in Factory.js when it requires Domanis.js const Domains = require('./Domains'); it returns an empty object.
Looking around on internet I found that it happens when there are a circular dependencies between modules (Require returns an empty object) but It doesn't seem the case here.
Any idea?
Finally, I got the the issue's origin. The empty object was due to a circular dependency derived by another require that was inside Domains.js
// Domains.js
const another_module= require("circular_dep_creator");
class Domains {
constructor (options = {}) {
....
}
}
module.exports = Domains;
// circular_dep_creator.js
const factory = require ('./Domains/Factory');
...
another stuff
So, this causes a circular dependency that creates an empty object
The setImmediate call will delay the loading of the required module until the browser has finished doing what it needs to do. This may cause some issues where you try to use this module before it is loaded, but you could add checks for that.
// produces an empty object
const module = require('./someModule');
// produces the required object
let module;
setImmediate(() => {
module = required('./someModule');
});

Why is the database snapshot undefined Firebase Admin Node Js?

The following code comes straight Firebase Functions getting started tutorial:
const functions = require('firebase-functions');
// The Firebase Admin SDK to access the Firebase Realtime Database.
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.addMessage = functions.https.onRequest((req, res) => {
let userid = 'afewfaewf';
let dummyJson = {key: 'value'};
let dbPath = '/' + userid;
admin.database().ref(dbPath).update({dummy: dummyJson}).then(snapshot => {
console.log('finished writing to Firebase database ');
console.log(snapshot === undefined);
res.redirect(303, snapshot.ref);
});
});
Here is the full output running it locally:
❯ firebase serve --only functions
=== Serving from '/Users/eric/AndroidStudioProjects/XXX/firebase-functions'...
i functions: Preparing to emulate HTTPS functions. Support for other event types coming soon.
Warning: You're using Node.js v7.7.1 but Google Cloud Functions only supports v6.9.1.
Server#addProtoService is deprecated. Use addService instead
✔ functions: addMessage: http://localhost:5002/xxx/us-central1/addMessage
info: User function triggered, starting execution
info: finished writing to Firebase database
info: true
error: (node:11005) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: Cannot read property 'ref' of undefined
(node:11005) DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
And on the cloud:
11:44:06.290 PM
warning
addMessage
TypeError: Cannot read property 'ref' of undefined at admin.database.ref.update.then.snapshot (/user_code/index.js:32:31) at process._tickDomainCallback (internal/process/next_tick.js:129:7)
TypeError: Cannot read property 'ref' of undefined
at admin.database.ref.update.then.snapshot (/user_code/index.js:32:31)
at process._tickDomainCallback (internal/process/next_tick.js:129:7)
11:44:06.289 PM
warning
addMessage
Unhandled rejection
11:44:06.288 PM
info
addMessage
true
11:44:06.283 PM
info
addMessage
finished writing to Firebase database
11:44:05.322 PM
outlined_flag
addMessage
Function execution started
Thanks #cartan for pointing me to the right direction
The original example "reads" from Firebase database so there is a snapshop value returned
My code on the other try to "writes" to Firebase database, there is no value returned but a call back instead.
I've changed my code to the following and everything works perfectly as expected:
admin.database().ref(dbPath).update({dummy: dummyJson}, function (err) {
console.log("done with error " + err);
res.status(200).send("success");
});

Resources