JSON.parse is not a function in node js - node.js

I'm new in node js and I'm trying to parse a JSON. This is what I've done so far:
const JSON = require("nodemon/lib/utils");
...
someFunction() {
let sens = [];
// sensor is the result of fs.readFileSync call and file is a json array
sens = JSON.parse(sensors);
It throws me:
JSON.parse is not a function.
How can I solve it?

Just comment out the very first line. JSON is built in already.
//const JSON = require("nodemon/lib/utils");

JSON is kind of a global object. It doesn't need to be required. So, just remove the line where JSON is required and it'll work fine.

Related

Using ipfs in javascipt: how to read an object the same way as dumpign it to file from command line and reading the file?

I have some arrow file that I am trying to read in javascript. Dumping it to file via the commanline: ipfs get HASH and then
fs = require('fs')
a = fs.readFileSync(HASH)
da = arrow.Table.from(a)
works fine.
Loading the cid (HASH)
ipfs = require('ipfs')
ipfs.create({repo: String(Math.random() + Date.now()) }).then(x=>node=x).then(
node=>node.object.get(HASH)
).then(x=>data=x)
Gives my something that has a data.Data buffer in some other format and it does not load into an arrow Table in the same way. How can I get the bytes in the same was as the readFileSync?
It turns out you need to use the ipfs cat method and that returns an async iterator so there is a small step to be aware of to get that into the arrow table.
I am not sure if there is a direct method for the get.
async function docat() {
var out = []
for await (const result of node.cat(has)) {
out.push(result)
}
return out
}

Getting error while reading json file using node.js

I am getting the following error while reading the json file using Node.js. I am explaining my code below.
SyntaxError: Unexpected token # in JSON at position 0
at JSON.parse (<anonymous>)
My json file is given below.
test.json:
#PATH:/test/
#DEVICES:div1
#TYPE:p1
{
name:'Raj',
address: {
city:'bbsr'
}
}
This json file has some # included strings . Here I need to remove those # included string from this file. I am explaining my code below.
fs.readdirSync(`${process.env['root_dir']}/uploads/${fileNameSplit[0]}`).forEach(f => {
console.log('files', f);
let rawdata = fs.readFileSync(`${process.env['root_dir']}/uploads/${fileNameSplit[0]}/${f}`);
let parseData = JSON.parse(rawdata);
console.log(parseData);
});
Here I am trying to read the code first but getting the above error. My need is to remove those # included lines from the json file and then read all the data and convert the removed lines to object like const obj ={PATH:'/test/',DEVICES:'div1',TYPE:p1}. Here I am using node.js fs module to achive this.
As you said, you need to remove those # lines from the JSON file. You need to code this yourself. To help with that, read the file into a string and not a Buffer by providing a charset to readFileSync.
const text = fs.readFileSync(path, 'utf8');
console.log(text);
const arr = raw.split("\n");
const noComments = arr.filter(x => x[0] !== "#"));
const filtered = noComments.join("\n");
const data = JSON.parse(filtered);
console.log(data);

module.exports variable producing undefined result

So one of the features of the bot I am working on is that I can be on discord 'discreetly', meaning that I can have the idle status but if a friend knows what command to call, they can actually check if I am there. So in my index file I am using module.exports to store the variable that will contain the info that I set. In the other file, I have an array of values that depending on the value from the variable, the bot will respond with one of the phrases from the array. The problem is that when using the variable, I get an undefined response. Any ideas what I am doing wrong? Important to note
I have checked to make sure by putting an actual number and have gotten the correct response so it is an issue with the exporting. I also have the correct file path. I have also assigned variable info a number and gotten the same result. Edit: tried using the filepath as part of the variable in the array like so and got the same error
//This got me a new result so progress.
const filepath = filepath;
console.log(filepath); //This gets me {}
message.reply(activity[info]); //undefined
//new attempt that failed
//paraphrasing the filepath assignment
const filepath = filepath;
activity[filepath.info]
//first attempt
//from index
var info = message.content;
module.exports = info;
//from the other file
var activity = ["Ready to play","Chilling","Doing work","afk","can talk"];
console.log(activity[info]);
message.reply(activity[info]);
how to get a variable from a file to another file in node.js
So this is the solution to my problem
//index
var info = message.content;
module.exports.info = message.content;
//other file
const filepath = filepath;
var activity = [array of different values];
message.reply(activity[index.info]);
Thank you slothiful for you time in trying to help me. I really appreciate it

How can I read json values from a file?

So basically I have these json values in my config.json file, but how can I read them from a .txt file, for example:
{"prefix": $}
This would set a variable configPrefix to $. Any help?
You can use require() to read and parse your JSON file in one step:
let configPrefix = require("./config.json").prefix;
Or, if you wanted to get multiple values from that config:
const configData = require("./config.json");
let configPrefix = configData.prefix;
If your data is not actually JSON formatted, then you have to read the file yourself with something like fs.readFile() or fs.readFileSync() and then parse it yourself according to whatever formatting rules you have for the file.
If you are going to be reading this file just as the start of the program then go ahead and use require or import if you have babel. just a tip, suround the require with a try catch block to handle possible errors.
let config
try {
config = require('path.to.file.json')
} catch (error) {
// handle error
config = {}
}
If you will be changing this file externally and you feel the need to source it then apart from reading it at the start you will need a function that uses fs.readFile. consider doing it like this and not with readFileAsync unless you need to block the program until you are done reading the config file.
After all of that you can do const configPrefix = config.prefix which will have the value '$'.

How does this npm build work?

https://github.com/apigee-127/swagger-converter
I see this code:
var convert = require('swagger-converter');
var fs = require('fs');
var resourceListing = JSON.parse(fs.readFileSync('/path/to/petstore/index.json').toString());
var apiDeclarations = [ JSON.parse(fs.readFileSync('/path/to/petstore/pet.json').toString()),
JSON.parse(fs.readFileSync('/path/to/petstore/user.json').toString()),
JSON.parse(fs.readFileSync('/path/to/petstore/store.json').toString())
];
var swagger2Document = convert(resourceListing, apiDeclarations);
console.log(JSON.stringify(swagger2Document, null, 2));
I'm confsued as to what exactly I'm supposed to do here to run this? Do I start a node http server?
To run the file you pasted, just save the code into a file like script.js. Then from the command line (with node installed) run node script.js. That will run the file. Here's a breakdown of what it's doing:
var convert = require('swagger-converter');
This line gets reference to the swagger-converter module that you linked to. That module is designed to allow you to convert swagger documents into JSON.
var fs = require('fs');
This line gets reference to the node built-in filesystem module (fs for short). It provides an API for interacting with the filesystem on your machine when the script is running.
var resourceListing = JSON.parse(fs.readFileSync('/path/to/petstore/index.json').toString());
This line could be broken down to:
var indexContent = fs.readFileSync('/path/to/petstore/index.json');
JSON.parse(indexContent.toString());
readFileSync returns the contents of the index.json file as a buffer object, which is easily turned into a simple string with the call to .toString(). Then they pass it to JSON.parse which parses the string and turns it into a simple JavaScript object.
Fun Fact: They could have skipped those steps with a simple var resourceListing = require('/path/to/petstore/index.json');. Node knows how to read JSON files and automatically turn them into JavaScript objects. You need only pass the path to require.
var apiDeclarations = [ JSON.parse(fs.readFileSync('/path/to/petstore/pet.json').toString()),
JSON.parse(fs.readFileSync('/path/to/petstore/user.json').toString()),
JSON.parse(fs.readFileSync('/path/to/petstore/store.json').toString())
];
This bit of code does the same thing as the resourceListing except it creates an array of three JavaScript objects based on those JSON files. They also could have used require here to save a bit of work.
Then finally they use the converter to do the conversion and then they log that data to the terminal where your script is running.
var swagger2Document = convert(resourceListing, apiDeclarations);
console.log(JSON.stringify(swagger2Document, null, 2));
JSON.stringify is the opposite of JSON.parse. stringify turns a JavaScript object into a JSON string whereas parse turns a JSON string into a JavaScript object.

Resources