Node sequelize throwing undefined error when checking if an object exists - mysql

Ok, so this is either very weird or I'm not understanding something that is happening. I am trying to load the sequelize library in node.
when trying to connect I'm using the CLI generated index.js file however this line:
if (config.use_env_variable) {
console.log('i ran');
var sequelize = new Sequelize(process.env[config.use_env_variable], config);
} else {
var sequelize = new Sequelize(config.db.database, config.db.username, config.db.password, {
dialect:config.db.dialect});
}
is giving me this error:
Cannot read property 'use_env_variable' of undefined
as far as I know that line is meant to see if this even returns anything so I don't understand why this is throwing that error?
UPDATE
config is invoked in a line above it, the whole file up to that point is:
'use strict';
var fs = require('fs');
var path = require('path');
var Sequelize = require('sequelize');
var basename = path.basename(__filename);
const config = require(path.join(__dirname,'../config/config.js'));
const db = {};
console.log(config);
if (config.use_env_variable) {
console.log('i ran');
var sequelize = new Sequelize(process.env[config.use_env_variable], config);
} else {
var sequelize = new Sequelize(config.db.database, config.db.username, config.db.password, {
dialect:config.db.dialect});
}
UPDATE added console.log of config on working version

After 3 days struggling with error, Today I was able to find a solution.
How did i solve?
I used JS trim() function to remove spaces.
for example
process.env.NODE_ENV === "development" // return false
why ?
"development " === "development" // return false because of extra space
process.env.NODE_ENV.trim() === "development" //return true
Here is my solution

It looks like you do not have config/config.json file or the path is incorrect. In model/index.js, you would have this line
let config = require(`${__dirname}/../../config/config.json`)[env];
or something like that. Make sure this path is the right path

Related

How to check if an HTML file is in a given directory, and then open that file with the referenced CSS and JS files within same directory

For my homework problem, I need to check if a file exists in a certain
directory "public", and then if it does, open it up through the
localhost in a browser. I wanted to use a function to check if the file
exists in directory, and then if true, send the file path to another function that'll open the file. This is all on my server.js file, and the HTML file I want to open along with the CSS and JS for the HTML file are all in my public directory.
This is using node.js. I need to run node server.js in the console, and then go to my localhost in a browser and see the displayed webpage with style and functionality. I've tried using fs.access and fs.existsSync. We are not allowed to use express on this assignment.
var http = require('http');
var fs = require('fs');
http.createServer(function(req, res) {
var filepath = 'public' + req.url;
if (req.url == '/index.html' || req.url == '/') {
fs.access(filepath);
}
}).listen(3000);
console.log("Server running on Port 3000...");
fs.access(filepath, (access) =>{
if (access) {
res.statusCode = 200;
sendFile(filepath, res);
}
else {
res.statusCode = 404;
sendFile('public/404.html', res);
}
});
function sendFile(path, res) {
fs.readFile(path, "utf8", function(data){
res.end(data);
});
}
I'm getting an error that says filepath is not defined (when I use it in the parameters when I call fs.access.
fs requires paths with a leading slash to work, so instead of var filepath = 'public' + req.url;, try
var filepath = '/public' + req.url;

Creating output for npm csvtojson

I'm trying to read in my .CSV file and output a .json file using npm's csvtojson
I am using the following code:
//Converter Class
var Converter = require("csvtojson").Converter;
var converter = new Converter({});
var fs = require("fs");
//end_parsed will be emitted once parsing finished
converter.on("end_parsed", function (jsonArray) {
console.log(jsonArray); //here is your result jsonarray
});
fs.createReadStream('data.csv')
.pipe(csv2json({
// Defaults to comma.
separator: '|'
}))
.pipe(fs.createWriteStream('dataOut.json'));
However, I'm running into the error "csv2json is not defined"
Does anyone know why I'm running into this error, despite including "csvtojson" on the first line?
cvs2json is not defined anywhere in your code. The cannocial example for cvs2json (from https://github.com/julien-f/csv2json) is:
var csv2json = require('csv2json');
var fs = require('fs');
fs.createReadStream('data.csv')
.pipe(csv2json({
// Defaults to comma.
separator: ';'
}))
.pipe(fs.createWriteStream('data.json'));
So the simple answer is to change your first line to var csv2json = require('csv2json');. However, this would cause an error in your attempt to have the end_parse event fire. To listen to that event, use the Node Stream eventing:
var stream = fs.createReadStream('data.csv')
.pipe(csv2json({
// Defaults to comma.
separator: '|'
}));
stream.on('end', function (jsonArray) {
console.log(jsonArray); //here is your result jsonarray
});
stream.pipe(fs.createWriteStream('dataOut.json'));
This is how I implement hope it helps.
let csv2Json = require('convert-csv-to-json');
let fileInputName = 'stores.csv';
let fileOutputName = 'stores.json';
csv2Json.fieldDelimiter(',').generateJsonFileFromCsv(fileInputName,
fileOutputName);
//To display json you created on terminal.
let json = csv2Json.getJsonFromCsv("stores.csv");
for(let i=0; i<json.length;i++){
console.log(json[i]);
}
Once you run the file, it is going to create the json file, if it is exists it is going to overwrite it.

directory not defined when looping through json file with node js

I am getting an error that "directory is not defined" I really don't know if it means in my code or my json file. Here is the json file which I checked the format with https://jsonformatter.curiousconcept.com/
[
{
"directory": "C:\\Users\\PCAdmin\\Downloads\\jsonin",
"dirID": "dir01"
},
{
"directory": "C:\\Users\\PCAdmin\\Downloads\\jsonout",
"dirID": "dir02"
}
]
Here is my code which based on examples I've seen should work yet I can't seem to get past the error;
'use strict';
var fs = require('fs');
var jsonObj = require("./jsonDirectories.json");
for(directory in jsonObj) {
console.log("Dir: "+jsonObj.directory);
}
I'm sure it's something stupid but any direction would be appreciated
The error means that the variable directory on line 4 of your code was not initialized. The following code will fix that bug:
'use strict';
var fs = require('fs');
var jsonObj = require("./jsonDirectories.json");
for (var dirInfo in jsonObj) {
console.log("Dir: " + dirInfo.directory);
}
However, this still does not do what you want, because the in operator does not work this way for arrays. The in operator is generally used to get the keys of objects (and then should still be used carefully).
To loop over your array of directory info, what you want is the following:
'use strict';
var fs = require('fs');
var jsonObj = require('./jsonDirectories.json');
jsonObj.forEach(function(dirInfo) {
console.log('Dir: '+dirInfo.directory);
}
(I also removed the mixed single and double quotes, which is good practice.)
You need to declare the directory variable before using it:
for (let item of jsonObj) {
// This line also needed fixing:
console.log("Dir: ", item.directory);
}
when you use for(directory in jsonObj) in node.js, directory will be assigned to the index of each of the items, not the value. so you can use jsonObj[directory] to get the directory.
But in my mind, this alternative is better:
jsonObj.forEach( function(directory) {
console.log("Dir: "+ directory);
});

ExpressJS POST cannot log body

After a lot of fiddling with upgrading versions and the different middleware/ways of using a body parser, I am still stuck.
I have an Iphone app which POSTs 2 things (2 separate things). First is an image, which works.
Second is a json object which i try to put into mongodb.
No matter what i do, i can't seem to log the contents of the request.
var express = require('express');
var logger = require('morgan');
var fs = require('fs');
var json = require('express-json');
var path = require('path');
var errorHandler = require('errorhandler');
MongoClient = require('mongodb').MongoClient,
Server = require('mongodb').Server,
CollectionDriver = require('./collectionDriver').CollectionDriver;
FileDriver = require('./fileDriver').FileDriver;
...
app.use(json());
//app.use(bodyParser.urlencoded({ extended: true }));
app.use(logger('dev'));
app.use(express.static(path.join(__dirname, 'public')));
...
app.post('/:collection', function(req, res) {
console.warn(req.body.poi.toString());
var object = req.body;
var collection = req.params.collection;
console.warn("Post: " + req.toString());
collectionDriver.save(collection, object, function(err,docs) {
if (err) { res.send(400, err); }
else { res.send(201, docs); }
});
});
I've tried logging (log, warn) req.body, req, etc. to no avail.
i'm using express-json and NOT url encoding, don't think need it.
morgan ouputs the following when i post
POST /pois 200 15.983 ms - 63
and nothing else!
It apparently cannot do it, as stated in this closed issue https://github.com/expressjs/morgan/issues/16
morgan is not intended for this kind of work. Try and use Winston instead, or simply console.log
This does it for me:
const express = require('express')
const app = express()
app.use(express.json())
var morgan = require('morgan')
morgan.token('response-body', (req, res) => {return JSON.stringify(req.body)}); // define 'response-body' token using JSON.stringify
app.use(morgan(':method :url :response-time :response-body')) //include newly defined ':response-body' token
app.post(/....)

How to read a sqlite3 database, using node js, synchronously?

exports.allProbes = function() {
var rows = db.all("SELECT * FROM probes;");
return rows;
};
main:
var json_values = allProbes();
Is it possible to do something like that?
I mean, without using a callback function: just, read data (sync mode) from the db. and return a json formatted output?
Thanks.
There are a few npm packages such as better-sqlite3 and sqlite-sync that allow for synchronous SQLite queries. Here's an example:
var sqlite = require("better-sqlite3");
var db = new sqlite("example.db");
var rows = db.prepare("SELECT * FROM probes").all();
console.log(rows);
You will not be able to do that with sqlite3. With sqlite3 module the only available mode of operation is asynchronous execution, and you will have to use a callback. Eg.
exports.allProbes = function(callback) {
db.all("SELECT * FROM probes;", function(err, all) {
callback(err, all);
});
};
Then in your code:
var json_values;
allProbes(function(err, all) {
json_values = all;
});
Check sqlite3 API Docs.
You have to install sql.js with npm install --save sql.js
Rest follow the below steps :
var fs = require('fs');
var sql = require('sql.js');
var bfr = fs.readFileSync('/tmp/db.sqlite');
var db = new sql.Database(bfr);
db.each('SELECT * FROM test', function (row) {
console.log(row);
});
More details you can get on the below this link : https://discuss.atom.io/t/how-to-access-a-local-db-on-windows-through-electron/22400/13