I'm having a hard time trying to get one value from a json file. Whatever I change it doesnt work. Can someone please help me and tell me what i am doing wrong? Here's my code
app.get('/results', function(req, res){
filePath = '/home/smath/'+req.query.id+'comp.json';
fs.readFile(filePath, function (err, data) {
if (err) {
throw err;
}
var jsondata = JSON.parse(data);
var score_comp = jsondata.scorecomplexes;
});
console.log(score_comp);
var jsonResponse = [];
jsonResponse.push({"text": "Complexes: "+score_comp+"/10"});
res.send(jsonResponse);
});
the json file i'm trying to read looks like this :
{"complexes":[{"Réponse 1":"a."},
{"Réponse 2":"a."},
{"Réponse 3":"c."}],
"scorecomplexes":2}
thanks already for your help !
Your variables "jsondata" and "score_comp" are declared locally for your function passed to app.get.. Therefore they are not accessible outside of that scope.
One solution is to declare the variables outside that "scope" and make the variables global, see example below:
//global variables
var jsondata;
var score_comp;
app.get('/results', function(req, res){
filePath = '/home/smath/'+req.query.id+'comp.json';
fs.readFile(filePath, function (err, data) {
if (err) {
throw err;
}
jsondata = JSON.parse(data);
score_comp = jsondata.scorecomplexes;
});
console.log(score_comp);
var jsonResponse = [];
jsonResponse.push({"text": "Complexes: "+score_comp+"/10"});
res.send(jsonResponse);
});
Related
It's my first JS therefore it may be very novice question.
I'd like to pass sql results made by SQLQUERY.js to MAIN.js but i don't know how to handle.
SQLQUERY.js
var mysql = require('mysql')
var db = require('./db/db.js');
var connection = mysql.createConnection(db);
var fs = require('fs')
connection.connect();
const sql = fs.readFileSync('./src/db/sql/selectTimeNotOnWork.sql').toString();
const sql2 = fs.readFileSync('./src/db/sql/selectTimeNotOnWorkCount.sql').toString();
var firstResult
var secondResult
connection.query(sql2,function (error, results, fields) {
if (error) throw error;
firstResult = results[0].count;
return firstResult;
});
connection.query(sql,function (error, results, fields) {
if (error) throw error;
secondResult= results[0].name
return secondResult;
});
exports ={firstResult,secondResult}
MAIN.JS
・・・・
require(./SQLQUERY.js)
controller.hears(['test'], botScope, async(bot, message) => {
console.log(firstResult)
console.log(secondResult)
await bot.reply(message, firstResult);
});
When you do a require() you can either require the whole export object or use destructuring.
So in MAIN.JS you would do something like:
{firstResult, secondResult} = require('./SQLQUERY.js')
And then those two values would be available in the MAIN.js code. At least that's how I do it when I need to import specific values from the export, not the entire object. I'm not an expert either so I don't know if a simple require('./SQLQUERY') would make these objects available.
I'm new to node and express but trying to dynamically fetch JSON based on the user's language settings. I need to figure out how to serve up the params:
I was thinking to try and set the "lang" param to its own variable and return that, but I am reading on SO that this is not best practice: Use variable's value as variable in javascript
var express = require("express");
var english = require('./Data/english.json');
var spanish = require('./Data/spanish.json');
var app = express();
app.use(function (req, res, next) {
console.log('inside of app.use');
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-
With, Content-Type, Accept");
next();
});
app.get("/:lang", function (req, res, next) {
const lang = req.params.lang;
console.log(lang)
res.send(lang);
});
app.listen(5000, () => console.log('Listening on port 5000!'))
I would like to be able to dynamically return the appropriate json file ! Any thoughts much appreciated.
TL;DR
Use the fs module to read you JSON files
Call JSON.parse() to parse the raw JSON
Choose the file according to var lang = req.params.lang using some kind of logic (for example, 'spanish' -> './data/spanish.json')
Code
const fs = require('fs');
// Supported languages
const supportedLanguages = ['english', 'spanish'];
app.get("/:lang", function (req, res, next) {
const lang = req.params.lang;
if (supportedLanguages.indexOf(lang) === -1) {
res.status(400).send('Language not supported');
} else {
fs.readFile(`./Data/${lang}.json`, (err, data) => {
// If error send a 500 status
if (err) res.status(500).send(err);
// Else parse the JSON file and send it
else res.send(JSON.parse(data));
});
}
});
It's simple to return json data with express.
Just use res.json({key: value , key2: value2}) instead of res.send
In your case, you can
const language = req.params.lang;
res.json({lang: lang})
you will receive a JSON object instead of text
I am new to sails js, I have to read json file in a sails generated controller and process the data in it. If its, express I generally use jsonfile module like this in app.js
let jsonfile = require('jsonfile')
let file = '/tmp/data.json'
jsonfile.readFile(file, function(err, obj) {
console.dir(obj)
})
How to do the same in sails js controller?
Oh, It seems as same as in express. I just tried able to read the data like this. In my controller
module.exports = {
readJsonFile: function (req, res) {
const jsonfile = require('jsonfile');
var file = './assets/json/data.json';
jsonfile.readFile(file, function (err, obj) {
if (err) {
res.json({err: err});
}
console.dir(obj)
res.json({obj: obj});
})
}
};
and its working. Thanks.
You can also use the readFileSync to read the JSON file
module.exports = {
index: async function (req, res) {
var filePath = './data/students.json';
let rawdata = fs.readFileSync(filePath);
let data = JSON.parse(rawdata);
sails.log("data", data);
return res.view('pages/index.ejs', data);
},
};
I have created an Azure time trigger function and i want to read a Json file with him. I did install read-json and jsonfile packages and tried with both, but it did not work. Here is an example function
module.exports = function (context, myTimer) {
var timeStamp = new Date().toISOString();
var readJSON = require("read-json");
readJSON('./publishDate.json', function(error, manifest){
context.log(manifest.published);
});
context.log('Node.js timer trigger function ran!', timeStamp);
context.done();
};
Here is de error:
TypeError: Cannot read property 'published' of undefined
at D:\home\site\wwwroot\TimerTriggerJS1\index.js:8:29
at ReadFileContext.callback (D:\home\node_modules\read-json\index.js:14:22)
at FSReqWrap.readFileAfterOpen [as oncomplete] (fs.js:365:13).
Json file is in same folder with the index.js. I assume that this error occurs because of the path './publishDate.json', if so how should i type a valid path?
Here's a working example that uses the built in fs module:
var fs = require('fs');
module.exports = function (context, input) {
var path = __dirname + '//test.json';
fs.readFile(path, 'utf8', function (err, data) {
if (err) {
context.log.error(err);
context.done(err);
}
var result = JSON.parse(data);
context.log(result.name);
context.done();
});
}
Note the use of __dirname to get the current working directory.
There is a quicker way than #mathewc's. NodeJS allows you to require json files directly without the explicit read -> parse steps nor without an async callback. So:
var result = require(__dirname + '//test.json');
According to this github issue the usage of __dirname wont work now, so updating the code from #mathewc with the update usage as per the wiki referred in the same issue.
replace __dirname with context.executionContext.functionDirectory
var fs = require('fs');
module.exports = function (context, input) {
var path = context.executionContext.functionDirectory + '//test.json';
fs.readFile(path, 'utf8', function (err, data) {
if (err) {
context.log.error(err);
context.done(err);
}
var result = JSON.parse(data);
context.log(result.name);
context.done();
});
}
I dont understand why I cant display my json data. I am new to javascript and I want to display the data in the json file to my index file.
I have used the express generator for all the files. I did read that I should add this FS code in my app.js, but I cant use the data variable in my index file in my view. Any help ?
var express = require('express');
var router = express.Router();
var fs = require('fs');
/* GET home page. */
router.get('/', function(req, res, next) {
var file = __dirname + '/public/list/list.json';
var data;
fs.readFile(file, 'utf8', function (err, data) {
if (err) {
console.log('Error: ' + err);
return;
}
data = JSON.parse(data);
console.log(data);
});
res.render('index', { title: data });
console.log(data);
});
module.exports = router;
here is my json file
{
"username":"xyz",
"password":"xyz#123",
"email":"xyz#xyz.com",
"uid": 1100
}
fs.readFile is asynchronous , so you should put res.render(..) inside his callback , because it will fired when the readFile function ends. So change your code to :
fs.readFile(file, 'utf8', function (err, data) {
if (err) {
console.log('Error: ' + err);
return;
}
data = JSON.parse(data);
console.log(data);
res.render('index', { title: data });
});
The above answer is correct, but there's also an alternative.
If you're using this file for your index page, it'd be used a lot. If the data isn't changing, you can simply require the JSON file at the top of your code and return it in the request.
var express = require('express');
var router = express.Router();
var list = require(__dirname + '/public/list/list.json');
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: list });
});
module.exports = router;
However, if that data does change frequently, reading the file is the way to go.