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);
},
};
Related
Trying to send form-data in postman and sequelize return error:
value cannot be null
But when send raw request with json all ok. Trying body-parser and multer, but nothing working
This is my index.ts
import express from "express";
import fileUpload from "express-fileupload"
...
const app = express()
const PORT = process.env.PORT || 5100
app.use(cors())
app.use(express.json())
app.use('/api', router)
app.use(fileUpload({}))
app.use(errorHandler)
const start = async () => {
try {
await sequelize.authenticate()
await sequelize.sync()
console.log(chalk.cyanBright('Successful conection to data base'));
app.listen(PORT, () => { console.log(chalk.cyanBright(`Server has been started on port ${PORT}`)) })
}
catch (e) {
console.log(e);
}
}
start()
And this is my controller
export const DeviceController = {
async create(req: Request, res: Response, next:nextType) {
try {
const { brandId, typeId, name, price } = req.body
const img = req.files
let filename = 'uuid.v4()' + '.jpg'
img?.mv(path.resolve(__dirname, '..', 'static', filename))
const device = await Models.Device.create({ brandId, typeId, name, price, img: filename })
return res.json(device)
} catch (error: any) {
next(ApiError.badRequest(error.message))
console.log(error);
}
app.use(express.json())
You have body parsing middleware for JSON request bodies.
You don't have body parsing middleware for multipart/form-data request bodies. The documentation for body-parser lists a several middlewares you could use.
Trying body-parser
… which says it doesn't support that format
and multart
… that doesn't appear to exist. Do you mean multiparty? Or maybe multer?
We can't tell you what you did wrong without seeing your attempt.
Re edit:
You said:
const img = req.files
img?.mv(path.resolve(__dirname, '..', 'static', filename))
But the documentation says:
console.log(req.files.foo); // the uploaded file object
The files property contains all the files, indexed by the the names given to them in the multipart request.
You're trying to read that collection of files as if it were a single file.
I'm a new learner to express js and sequelizejs. I successfully migrate table in my database so the connection is fine I guess.
Here is my code.
https://github.com/Picks42/express-test
Please review this file
https://github.com/Picks42/express-test/blob/master/models/user.js
Then review this one
https://github.com/Picks42/express-test/blob/master/controller/test.js
Let me know what's the issue.
// all the models using your index.js loader
const models = require('../models');
// the user model, note the capital User since
const M_Bank = models.User;
exports.getTest = function(req,res){
return M_Bank
.findAll()
// don't use M_Bank here since you are getting an array of Instances of the Model
.then(users => res.status(200).send(users))
.catch((error) => {
console.log(error.toString());
res.status(400).send(error)
});
/* this will never execute because it is after the return
exports.index = function (request, response, next) {
response.json((M_Bank.findAll()));
};
*/
};
If you have the option of using async/await it makes for more readable code.
const models = require('../models');
const M_Bank = models.User;
exports.getTest = async function(req, res) {
try {
const users = await M_Bank.findAll();
return res.status(200).send(users);
} catch (err) {
console.log(err.toString());
return res.status(400).send(err);
}
};
You should get rid of the .User field in the 3rd line. because you've exported User itself from the models/user file.
Also, I recommend you not to mess with variables names. M_Bank variable doesn't speak itself
const M_Bank = require('../models/user');
exports.getTest = function(req,res){
return M_Bank
.findAll()
.then(M_Bank => res.status(200).send(M_Bank))
.catch((error) => {
console.log(error.toString());
res.status(400).send(error)
});
exports.index = function (request, response, next) {
response.json((M_Bank.findAll()));
};
};
I would like to scrape this page: calendar events
for specific data, like formattedDate and description. How do I go about that in a module in Node.JS. I am having a hard time understanding the process in Node.JS.
Any help would go a long way, thanks in advance.
it's pretty simple, you can import the request module and use it. For example, see code below.
const request = require("request");
request("MY_URL", (error, response, body) => {
console.log('body:', body);
});
Also, you can try this here, on Repl.it
First of all, you need to parse your JSON, this allows you to access fields from received json.
const data = JSON.parse(body);
Now, if you want to access some information about an event you need to loop events and access what you need, something like:
const events = data.bwEventList.events;
events.map((data, index) => console.log(data.calendar))
Final code also on Repl.it
from nodeJS docs here
const http = require('http');
http.get('http://umd.bwcs-hosting.com/feeder/main/eventsFeed.do?f=y&sort=dtstart.utc:asc&fexpr=(categories.href!=%22/public/.bedework/categories/sys/Ongoing%22%20and%20categories.href!=%22/public/.bedework/categories/Campus%20Bulletin%20Board%22)%20and%20(entity_type=%22event%22%7Centity_type=%22todo%22)&skinName=list-json&count=30', (res) => {
const { statusCode } = res;
const contentType = res.headers['content-type'];
let error;
if (statusCode !== 200) {
error = new Error('Request Failed.\n' +
`Status Code: ${statusCode}`);
}
if (error) {
console.error(error.message);
// consume response data to free up memory
res.resume();
return;
}
res.setEncoding('utf8');
let rawData = '';
res.on('data', (chunk) => { rawData += chunk; });
res.on('end', () => {
try {
const parsedData = JSON.parse(rawData);
console.log(parsedData["bwEventList"]["resultSize"]);
} catch (e) {
console.error(e.message);
}
});
}).on('error', (e) => {
console.error(`Got error: ${e.message}`);
});
see console.log(parsedData["bwEventList"]["resultSize"]);
slice parsedData as an array until you get what you want
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);
});
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();
});
}