directory not defined when looping through json file with node js - json

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);
});

Related

Confused on how notes = JSON.parse(noteString);

var addnote = function (title, body) {
var notes = [];
var note = {
title: title,
body: body
}
need explanation on the two lines under try
try {
var noteString = fs.readFileSync("data.json");
notes = JSON.parse(noteString);
} catch (e) {
}
And explanation on how duplicateNotes works ..
var duplicateNotes = notes.filter(function(note){
return note.title === title
})
if (duplicateNotes.length === 0) {
notes.push(note);
fs.writeFileSync("data.json", JSON.stringify(notes));
}
}
JSON.parse converts a JSON object to String.
{
field1:field1Value,
field2:fieldValue
}
If this is in Json format you can access it's elements using JSONObjectName.fieldName
But,if it's converted to String it looses it's JSON properties. You can't access fields in same way. Output will act like String.
need explanation on the two lines under try
var noteString = fs.readFileSync("data.json");
There are two kinds of response back asynchronous and synchronous. Synchronous call is like you will not start playing until you get a pass and score a goal. But, Asynchronous call is like you start playing with your friend but, you run near him and, there is a promise you won't shoot until you get the ball.
readFileSync will read the file and the next line will wait until it gets the pass.JSON.parse() will convert file content to JSON object.
And explanation on how duplicateNotes works ..
var duplicateNotes = notes.filter(function(note){
return note.title === title
})
Whenever a match is found , that element in notes will be pushed to duplicate note. That's all.

Node sequelize throwing undefined error when checking if an object exists

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

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.

How to use streams to JSON stringify large nested objects in Node.js?

I have a large javascript object that I want to convert to JSON and write to a file. I thought I could do this using streams like so
var fs = require('fs');
var JSONStream = require('JSONStream');
var st = JSONStream.stringifyObject()
.pipe(fs.createWriteStream('./output_file.js'))
st.write(large_object);
When I try this I get an error:
stream.js:94
throw er; // Unhandled stream error in pipe.
^
TypeError: Invalid non-string/buffer chunk
at validChunk (_stream_writable.js:153:14)
at WriteStream.Writable.write (_stream_writable.js:182:12)
So apparently I cant just write an object to this stringifyObject. I'm not sure what the next step is. I need to convert the object to a buffer? Run the object through some conversion stream and pipe it to strinigfyObject
JSONStream doesn't work that way but since your large object is already loaded into memory there is no point to that.
var fs = require('fs-extra')
var file = '/tmp/this/path/does/not/exist/file.txt'
fs.outputJson(file, {name: 'JP'}, function (err) {
console.log(err) // => null
});
That will write the JSON.
If you want to use JSONStream you could do something like this:
var fs = require('fs');
var jsonStream = require('JSONStream');
var fl = fs.createWriteStream('dat.json');
var out = jsonStream.stringifyObject();
out.pipe(fl);
obj = { test:10, ok: true };
for (key in obj) out.write([key, obj[key]]);
out.end();
Well the question is quite old but still valid for nowadays, I faced same issue but solved it using this JsonStreamStringify package.
const { JsonStreamStringify } = require("json-stream-stringify");
Now,
x = new JsonStreamStringify(cursor).pipe(res);
x.on("data", (doc) => {
res.write(doc);
});
Here you can read your file using fs and then write the above code. 'cursor' will be pointing to your file.
In this way, you can stream your file in valid JSON Format.
For Docs:
https://www.npmjs.com/package/json-stream-stringify

Trying to interpret the Node-Neo4j API

I'm pretty new to coding so forgive me if my code is unreadable or my question simplistic.
I am trying to create a little server application that (amongst other things) displays the properties of a neo4j node. I am using node.js, Express and Aseem Kishore's Node-Neo4j REST API client, the documentation for which can be found here.
My question stems from my inability to fetch the properties of nodes and paths. I can return a node or path, but they seem to be full of objects with which I cannot interact. I poured through the API documents looking for some examples of how particular methods are called but I found nothing.
Ive been trying to call the #toJSON method like, "db.toJSON(neoNode);" but it tells me that db does not contain that method. I've also tried, "var x = neoNode.data" but it returns undefined.
Could someone please help me figure this out?
//This file accepts POST data to the "queryanode" module
//and sends it to "talkToNeo" which queries the neo4j database.
//The results are sent to "resultants" where they are posted to
//a Jade view. Unfortuantly, the data comes out looking like
// [object Object] or a huge long string, or simply undefined.
var neo4j = require('neo4j');
var db = new neo4j.GraphDatabase('http://localhost:7474');
function resultants(neoNode, res){
// if I console.log(neoNode) here, I now get the 4 digit integer
// that Neo4j uses as handles for nodes.
console.log("second call of neoNode" + neoNode);
var alpha = neoNode.data; //this just doesn't work
console.log("alpha is: " +alpha); //returns undefined
var beta = JSON.stringify(alpha);
console.log("logging the node: ");
console.log(beta);// still undefined
res.render("results",{path: beta});
res.end('end');
}
function talkToNeo (reqnode, res) {
var params = {
};
var query = [
'MATCH (a {xml_id:"'+ reqnode +'"})',
'RETURN (a)'
].join('\n');
console.log(query);
db.query(query, params, function (err, results) {
if (err) throw err;
var neoNode = results.map(function (result){
return result['a']; //this returns a long string, looks like an array,
//but the values cannot be fetched out
});
console.log("this is the value of neoNode");
console.log(neoNode);
resultants(neoNode, res);
});
};
exports.queryanode = function (req, res) {
console.log('queryanode called');
if (req.method =='POST'){
var reqnode = req.body.node; //this works as it should, the neo4j query passes in
talkToNeo(reqnode, res) //the right value.
}
}
EDIT
Hey, I just wanted to answer my own question for anybody googling node, neo4j, data, or "How do I get neo4j properties?"
The gigantic object from neo4j, that when you stringified it you got all the "http://localhost:7474/db/data/node/7056/whatever" urls everywhere, that's JSON. You can query it with its own notation. You can set a variable to the value of a property like this:
var alpha = unfilteredResult[0]["nodes(p)"][i]._data.data;
Dealing with this JSON can be difficult. If you're anything like me, the object is way more complex than any internet example can prepare you for. You can see the structure by putting it through a JSON Viewer, but the important thing is that sometimes there's an extra, unnamed top layer to the object. That's why we call the zeroth layer with square bracket notation as such: unfilteredResult[0] The rest of the line mixes square and dot notation but it works. This is the final code for a function that calculates the shortest path between two nodes and loops through it. The final variables are passed into a Jade view.
function talkToNeo (nodeone, nodetwo, res) {
var params = {
};
var query = [
'MATCH (a {xml_id:"'+ nodeone +'"}),(b {xml_id:"' + nodetwo + '"}),',
'p = shortestPath((a)-[*..15]-(b))',
'RETURN nodes(p), p'
].join('\n');
console.log("logging the query" +query);
db.query(query, params, function (err, results) {
if (err) throw err;
var unfilteredResult = results;
var neoPath = "Here are all the nodes that make up this path: ";
for( i=0; i<unfilteredResult[0]["nodes(p)"].length; i++) {
neoPath += JSON.stringify(unfilteredResult[0]['nodes(p)'][i]._data.data);
}
var pathLength = unfilteredResult[0].p._length;
console.log("final result" + (neoPath));
res.render("results",{path: neoPath, pathLength: pathLength});
res.end('end');
});
};
I would recommend that you look at the sample application, which we updated for Neo4j 2.0
Which uses Cypher to load the data and Node-labels to model the Javascript types.
You can find it here: https://github.com/neo4j-contrib/node-neo4j-template
Please ask more questions after looking at this.