Is it possible to create a Collection in Postman that executes a few hundred requests to an API and download all responses in json?
If it is possible, how to do that?
If it is not possible, what available tools do we have ? (free and open source)
You can use Newman as a library and the NodeJS fs module to do this:
const newman = require('newman'),
fs = require('fs');
newman.run({
collection: '<Collection File Or Link>'
}).on('request', (err, args) => {
fs.writeFile(`./${args.item.name}.json`, args.response.stream, (err) => {
if (err) {
console.error(err);
}
});
});
This will run all the results in your Collection and then save each of the responses to a JSON file. The filename will be the name of the request.
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 actually working on a NodeJS API that send mail.
index.handlebars is a template that I want to use everytime that I need to send an email
So I use Node File Systeme (fs) to readFileSync() and then replace() the data need before sending email to the user.
Here is an exemple :
const readMe = fs.readFileSync('./mails/index.handlebars', 'utf8', (error, data) => {
if (error) {
console.log(error);
} else {
data = data.toString('utf8').replace('{%CONFIRMATION%}', "SELLER AS VALIDATE YOUR ORDER")
return data
}
})
console.log(readMe);
First sometimes, replace() is not working for me and nothing happend. I don't know why.
But when it work, my goal is to not overwrite index.handlebars. What I mean by that is replace() all the stuff and then send it BUT keep index.handlebars as it was before replace().
Is it possible ?
Thanks a lot.
The fs module provides fs.readFile (read file asynchronously, takes a callback) and fs.readFileSync (read synchronous, does not require a callback).
You are currently mixing up the 2 signatures in trying to do a synchronous read with a callback.
To use readFileSync (synchronous), you should
// synchronous without callback
const data = fs.readFileSync('./mails/index.handlebars', { encoding: 'utf8', flag: 'r' })
const replaced = data.replace('{%CONFIRMATION%}', "SELLER AS VALIDATE YOUR ORDER")
console.log(replaced);
For readFile (asynchronous), you use the callback
// asynchronous with callback
fs.readFile('./mails/index.handlebars', 'utf8', (error, data) => {
if (error) {
console.log(error);
} else {
data = data.replace('{%CONFIRMATION%}', "SELLER AS VALIDATE YOUR ORDER")
// perform necessary operations on data
console.log(data);
}
})
This is what my code looks like:
'use strict';
process.env.AWS_PROFILE
// Load the AWS SDK for Node.js
const AWS = require('aws-sdk');
// Create EC2 service object
var ec2 = new AWS.EC2({apiVersion: '2016-11-15'});
// Load credentials and set region from JSON file
AWS.config.loadFromPath('/Users/testuser/.aws/credentials');
// Load in security group parameters
const securityParams = require('./securityParams.json');
module.exports = {
//Exports creation of Security Groups
CreateSecurityGroup: (req, res) => {
ec2.createSecurityGroup(securityParams, function(err, data) {
if (err) {
return (console.log("Error", err));
}
// Pass the Json as a parameter in this function
ec2.authorizeSecurityGroupIngress(securityParams, function(err, data) {
if (err) {
res.serverError(err, err.stack);
} else {
res.ok(data);
console.log('Ingress Security Rules Created');
}
})
// Pass the Json as a parameter in this function
ec2.authorizeSecurityGroupEgress(securityParams, function(err, data) {
if (err) {
res.serverError(err, err.stack);
} else {
res.ok(data);
console.log('Egress Security Rules Created');
}
})
})
}
}
I'm trying to have the script load configurations from two files; one aws credentials file, and one json. However its throwing errors on the credentials file which looks like this:
[default]
aws_access_key_id=**************
aws_secret_access_key**************
I'm not sure what I'm missing to get it to read the properties in correctly.
Here is the error I'm seeing:
undefined:1
[default]
^
SyntaxError: Unexpected token d in JSON at position 1
at JSON.parse (<anonymous>)
credentials is a plain Ascii file, it's not json file
// Load credentials and set region from JSON file
AWS.config.loadFromPath('/Users/testuser/.aws/credentials');
You can check file type with command file /Users/testuser/.aws/credentials
sample snippet to read props file and set AWS config
var PropertiesReader = require('properties-reader');
var AWS = require('aws-sdk')
var properties = PropertiesReader('/Users/username/.aws/credentials');
AWS.config.update({
accessKeyId : properties.get('aws_access_key_id'),
secretAccessKey : properties.get('aws_secret_access_key'),
region : 'us-west-2'
})
console.log(AWS.config)
Ref:https://www.npmjs.com/package/properties-reader
I need to write a field from my mongodb database to a json file. Using node js. How to go about it? I haven't found anything helpful.
Try this
var exportDocuments = function (db, callback) {
// Get the documents collection
var collection = db.collection('documents');
// Find some documents
collection.find({}).toArray(function (err, docs) {
require('fs').writeFile('yourFileName.json', JSON.stringify(docs), function (error) {
if (error) return callback(error);
callback();
});
});
}
Using node.js I am attempting to load a .json file (file) and have it viewed on a web browser. So far I have been able to create a JSON object (obj) and viewed the JSON string of that object on the web browser. However, when I attempt to load the file I get the file link and not the file itself. Below is the code:
var jf = require('jsonfile');
var jsonfn = function(request, response) {
var file = '/home/ubuntu/public/json/foods.json';
var obj = {name: 'JP'};
jf.writeFile(file, obj, function(err) {
console.log(util.inspect(jf.readFileSync(file)));
})
response.json(obj);
};
Can anyone provide advice for me being able to load a JSON file and create a response to allow me to view the file in the web browser?
jf.readFile(file, function(err, obj) {
if (err) return response.send(500);
response.json(obj);
});
// or ...
require('fs').readFile(file, function(err, data) {
if (err) return response.send(500);
response.setHeader('Content-Type', 'application/json');
response.send(data);
});