Custom Module DB Variable Export - NodeJS - node.js

I've Got a Small Script That Runs Continuously On My Server.
I'd Like To Connect It To a DB To Get Some Data For The Script's Operation. So, I Required The Custom Model I Built, And Node Recognises It - It Does Not Send Back An Error With "Module Not Found".
The DB Script Works, And Pulls Exactly What I Need From The DB. This Is How It Looks (Assume The Connection Is Open - This Is Just The Query & Response Code):
connection.query(sql, function (err,rows){
//Handle Errors
if(err){
throw err;
}
//If Successful - Log Results For Now (Change To Export Results)
else{
//console.log(rows);
rows = exports.rows;
}
});
Unfortunately, Whenever I Call DB.rows In My Main Script, It Returns undefined.
Am I Exporting It Wrong Or The Problem Lies Deeper Within?

Related

NodeJS FTP not throwing error when trying to delete non-existent file

I am working with ftp-npm and I am currently facing a weird bug...
I have a method called refreshStore that contains this part of code :
c.delete('/pathToMyFileOnFTPServer', function(err) {
console.log('117');
if (err) throw err;
});
This is not throwing error and even not logging the '117' string even though my file does not exist on the server... Why is this like this ?
Thanks all!

How to write logs in node js

Recently i got a work to write log messages to my node js project.I am not sure about what exactly a log message mean,generally for a function we write 2 cases like below
exports.inserttopic = function (req, res) {
var topics = new Topics(req.body);console.log(topics)
topics.save(function (err, result) {
if (err) {
console.log(err);
return err;
}
if (result) {
data = { status: true, error_code: 0, result: result, message: 'Inserted successfully' };
}
res.json(data);
});
};
From the above code,i put console.log(err) for error case .is this a log message?If not how does log message s different from it?I heared something that log messages should be ride into a file.How can i do it,i surfed in google but i didnt come to end in understanding.I really troubled about it.Can anyone suggest me some help and post some good articles.Thanks.
A "log message" is only some Text Information which is offered by a program.
The message can be written to different output channels.
E.g. you are using the Console channel which is bound on the running program. This means when the program ends the log message may get lost if you don't save it explicitly (e.g. with a text-editor in a file).
The better way is to log into a so called "log-file".
You can write your own function which writes to a file or you can use some logging-framework.
The benefit on a logging framework is, that it mostly offers you the ability to choose, which output channel you prefer (for example also Database!), how the logging message has to look like (e.g. Date and Time at the beginning of each line) and that it offers you different severities.
Severities can be for example of type:
Error
Info
Debug
The Logging Framework (or your configuration) then decides how to handle the different severities.
Write the severities in different Logfiles (debug.log, error.log)
Write only messages over the configured Severity Level (e.g. Level Info skips debug messages)
...

gcloud Datastore transaction issue using nodejs

I am using nodejs to contact the google datastore. This is my code:
dataset.runInTransaction(function(transaction, done,err) {
// From the `transaction` object, execute dataset methods as usual.
// Call `done` when you're ready to commit all of the changes.
transaction.save(entities, function(err) {
if(err){
console.log("ERROR TRNASCTION");
transaction.rollback(done);
return;
}else{
console.log("TRANSACTION SUCCESS!");
done();
}
});
});
If the save was not successful, I would like the transaction to rollback and if it was I want it to commit. The problem I am facing is that neither of them seem to be running, just no output on the console. Nothing is being sent to my database so I would assume at least the 'if(err)' condition would run but it doesn't. I am new to glcoud so I am not sure if I am doing something wrong here? I am following the doc at https://googlecloudplatform.github.io/gcloud-node/#/docs/v0.26.0/datastore/transaction?method=save.
In the context of a transaction, the save method doesn't actually need a callback. The things you wish to save are queued up until you call done(). Calling done will commit the transaction.
You can then handle errors from the commit operation in a second function passed to runInTransaction. See https://googlecloudplatform.github.io/gcloud-node/#/docs/v0.26.0/datastore/dataset?method=runInTransaction for examples of that.
--
Just mentioning this since it relates to the rollback part: https://github.com/GoogleCloudPlatform/gcloud-node/issues/633 -- we're waiting on an upgrade to Datastore's API before tackling that issue.

Node.js fs.writeFile returning unexpected token syntax error

The following node.js test code fragment works perfectly when run for the first time (creating the file), but fails to overwrite the file once it's already created and instead generates a syntax error when the code is run a second time: 'SyntaxError: Unexpected token'. The Node docs say that fs.writeFile "Asynchronously writes data to a file, replacing the file if it already exists. data can be a string or a buffer." Not sure what I'm doing wrong or missing regarding this, thanks! I'm on Node 4.2.2
fs.writeFile('message.txt', 'Hello Node.js', 'utf8', function (err) {
if(err){
throw err;
}
else{
console.log('It\'s saved!');
}
});
Based on the stack trace you've supplied in your comment, the error you're seeing is a problem with another part of your code, not the snippet you've posted.
Furthermore, it appears that you (or some other function is doing so behind the scenes) are attempting to JSON.parse() some string, but the string is not actually (valid) JSON (perhaps it is HTML or some other type). If you are getting this data from an HTTP response, you may want to check the value of res.headers['content-type'] first because attempting to use JSON.parse().

node.js File upload configurations

No Matter how much I've searched and changed and toyed over the last 24 hours, I simply can not find the right combination of settings that allows Node.js to upload multiple files.
My setup is quite simple - I have a form interface that posts multipart content (files) to an endpoint.. lets call it: /theendpoint
and this end point is supposed to parse the multiple files. However, during the parsing, there are various events that need to be called once the file is uploaded.
I'm currently using the express.bodyParser({ uploadDir:'/tmp', keepextensions:true, defer:true}); in the app configuration.
Using the following method, I am trying to parse the file, but the problem is
Only 2 files will begin uploading, and will not complete (ie. the progress bar hangs near the end without fully completing).
The other files to be uploaded by the form (item 3+) do not even begin to upload to the server.
It seems to be some sort of asynchronus holdup, however I can't properly interpret the problem. Some of the code used at the upload endpoint are as follows:
// This applies to /theendpoint route. Using Express.
exports.theendpoint = function(req,res){
console.log(req.files);
fs.readfile(uploadPath, function(err,data){
if(err) throw err;
fs.writeFile(newFilePath, data, function(err){
// Series of checks and definitions
// Database connection
// Conditional executions
fs.unlink(req.files.file.path, function(err){
if(err) throw err;
console.log('Deleted');
});
});
});
};
Obviously I've left out some of the code here. If anyone can help - is this structure workable?
You should know that items in the commented section.. ie DB connection etc. are asynchronus tasks.
after
fs.unlink(req.files.file.path, function(err){
if(err) throw err;
console.log('Deleted');
});
add
res.redirect("back");
and it works!

Resources