how to skip the first optional param but insert the next one - javascript

I am using the following code got it from https://docs.min.io/docs/javascript-client-api-reference.html
var Fs = require('fs')
var file = '/tmp/40mbfile'
var fileStream = Fs.createReadStream(file)
var fileStat = Fs.stat(file, function(err, stats) {
if (err) {
return console.log(err)
}
minioClient.putObject('mybucket', '40mbfile', fileStream, stats.size, function(err, objInfo) {
if(err) {
return console.log(err) // err should be null
}
console.log("Success", objInfo)
})
})
and it works fine. However I need to send the metadata as well but not size and both are optional
How can I send the optional metadata but no size in a way that the library can still works properly?
I want something like this
minioClient.putObject('mybucket', '40mbfile', fileStream, metadata, function(err, objInfo) {

I'm not familiar with this library specifically, but the standard way of skipping optional values is just passing the value as null:
minioClient.putObject('mybucket', '40mbfile', fileStream, null, meta, function(err, objInfo) {
if(err) {
return console.log(err) // err should be null
}
console.log("Success", objInfo)
})

Related

How to properly use nodejs soap

My code looks like this:
soap.createClient(url, function(err, client) {
if(err) {
res.status(500);
return res.send(err);
}
client.GetMemberPIN({pUserName: 'r'}, function(error, result) {
if(error) {
res.status(500);
return res.send(error)
}
return res.send(result);
});
});
I tried running it and it returns this error?
{
"code": "ECONNRESET"
}
I'd suggest testing a few things:
Make sure the url points to a valid WSDL document, e.g. https://www.crcind.com/csp/samples/SOAP.Demo.CLS?WSDL=1
Log which part of the process fails, e.g. the client creation, or the function call.
Here's a working example testing against a public server, this might help you to understand what could be going wrong with your code:
const soap = require('soap');
const url = 'https://www.crcind.com/csp/samples/SOAP.Demo.CLS?WSDL=1';
const args = { id: 1 };
soap.createClient(url, function(err, client) {
if (err) {
console.error("An error occurred creating client:", err);
return;
}
client.FindPerson(args, function(err, response) {
if (err) {
console.error("An error occurred calling client.FindPerson:", err);
return;
}
console.log("client.FindPerson: response:", response);
});
});

ReferenceError: err is not defined mongoose mongodb

When I run this code, it returns an error saying that err is not defined
here is my code
app.post('/tinder/cards', (req, res) => {
const dbCard = req.body;
Cards.create(dbCard, (err, data) => {
if (err) {
res.status(500).send(err);
} else {
res.status(201).send(data);
}
});
app.get('/tinder/cards', (req, res) => {
Cards.find(err, data => {
if (err) {
res.status(500).send(err);
} else {
res.status(200).send(data);
}
});
Here is my definition of the MongoDB schema:
import mongoose from 'mongoose';
const cardSchema = mongoose.Schema({
name: String,
imgUrl: String,
});
export default mongoose.model('cards', cardSchema);
Someone, please help me fix this thank you!
Change
Cards.find(err, data =>
here it's looking for the filter/query as the 1st Parameter which err variable which is not defined so you're getting the ReferenceError.
To
Cards.find(query, (err, data) => { // 1st Parameter should be filter/query
https://mongoosejs.com/docs/api.html#model_Model.find
Model.find()
Parameters
filter «Object|ObjectId»
[projection] «Object|String|Array<String>» optional fields to return, see Query.prototype.select()
[options] «Object» optional see Query.prototype.setOptions()
[callback] «Function»

Add square brackets at beginning and end of json file using Node.js

I have a JSON file and I want to add a square bracket at the beginning and end of JSON.
eg.
Input
{
"name": "Ram",
"age": 25
},
{
"name": "Laxman",
"age": 24
}
Expected output:
[
{
"name": "Ram",
"age": 25
},
{
"name": "Laxman",
"age": 24
}
]
this is a sample response, I am having a large JSON data in a file.
The best option (in my opinion) would be to open a new reader;
Open a BufferedReader
Append [
Append JSON file
Append ]
From there you can use the BufferedReader or write it into a new file.
So, we need to consider 2 situations here:
The first one is when you're responsible for creating this input file. Then, assuming you already have those objects in an array and just need to save the array itself instead of the individual objects using a for.
const fs = require('fs')
const objs = [ { "name": "Ram","age": 25},{ "name": "Laxman","age": 24} ]
const jsonData = JSON.stringify(objs)
fs.writeFile("inputFile.json", jsonData, (err) => {
if (err) {
console.log(err);
}
});
The second situation if when you don't have control to modify the input file in its creation, and are just transforming the file previously saved. In this case you'll need to completely rewrite the file due to fs limitations for positional "inserts". To do so, read the previous file into a buffer, prepend it with the opening bracket "[" and append the closing one "]" at the end. As follows:
const fs = require('fs')
const filename = 'inputFile.json'
const fileBuffer = fs.readFileSync(filename)
const newBuffer = Buffer.concat([Buffer.from('['), fileBuffer, Buffer.from(']')])
fs.writeFileSync(filename, newBuffer)
I had the same problem and after hours of searching, I found nothing so I wrote a custom code that works like a charm. Hope it helps!:)
const fs = require('fs')
var response = {};
const fsOps = async (params) => {
try {
const path = "tmp/" + params.user + ".json";
const data = params.data;
const chunksNumber = params.chunksNumber;
var chunkID = params.chunkID;
//ON FIRST CHUNK ADD [
if (chunkID === 1) {
fs.appendFile(
path, ("["), 'utf-8', function (err) {
if (err) throw err;
}
);
if (chunksNumber !== 1)
fs.appendFile(
path, JSON.stringify(data, null, 2) + ',', 'utf-8', function (err) {
if (err) throw err;
}
);
}
//WRITE CHUNKS
if (chunkID !== 1 && chunkID < chunksNumber) {
fs.appendFile(
path, JSON.stringify(data, null, 2) + ',', 'utf-8', function (err) {
if (err) throw err;
}
);
}
//ON LAST CHUNK WRITE THE LAST CHUNK AND ADD ]
if (chunkID === chunksNumber) {
console.log("LAST CHUNK")
fs.appendFile(
path, JSON.stringify(data, null, 2), 'utf-8', function (err) {
if (err) throw err;
}
);
//APPEND ] on the end of file
fs.appendFile(
path, ("]"), 'utf-8', function (err) {
if (err) throw err;
}
);
//READ THE FILE
fs.readFile(path, (err, data) => {
if (err) {
console.error(err)
return;
} else {
response = data;
}
})
//DELETE FILE
fs.unlink(path, (err) => {
if (err) {
console.error(err)
return err
}
})
}
//Return object with all the part data
return JSON.parse(response);
} catch (err) {
//IN CASE OF ERROR DELETE FILE
fs.unlink(path, (err) => {
if (err) {
console.error(err)
return err
}
})
return err;
}
}
module.exports = fsOps;

Mongodb find() return undefined

When ever I try to just use a simple find() for my mongodb it returns undefined.
var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017/local';
MongoClient.connect(url, function (err, db) {
db.collection('pokemon').find({ $search: { $text: 'Pikachu' } }).toArray(function(err, data){ console.log(data) })
});
EDIT:
Turns out I never created an index by putting
db.collection('pokemon').createIndex({Name: 'text'})
before all the code.
First of all, every time where you have:
function(err, data){ console.log(data) }
you should check errors:
function (err, data) {
if (err) {
console.log('Error:', err);
} else {
console.log('Data:', data);
}
}
Then you will probably see what's going on.
This is also true for the database connection itself - instead of:
MongoClient.connect(url, function (err, db) {
// use db here
});
you should handle errors:
MongoClient.connect(url, function (err, db) {
if (err) {
// handle errors
} else {
// use db here
}
});
If you don't handle errors then don't be surprised that you don't know why you don't get values.

How to read file in Node?

I want to read file but if file not available on particular path than gives an error.I want to create a file if not exist and get data value is null. I used these code but not working please any one help me?
fs.readFile(path, 'utf8', function (err,data) {
if (err) {
return console.log(err); //Here throw error if not available
}
console.log(data);
fileData = data;
});
I used below code it's also not working.I want read all data from file what should i put on '?' in following code?
fs.open(path, 'w+', function(err, data) {
if (err) {
console.log("ERROR !! " +err);
} else {
fs.read(data, ? , 0, ? , null, function(err) {
if (err) console.log("ERROR !! " +err);
});
}
});
There is an error in your first code snippet, try:
fs.readFile(path, {encoding: 'utf8'}, function (err, data) {
if (err) throw err;
console.log(data);
});
The error was in the "encoding utf". It should be an object.
See: http://nodejs.org/api/fs.html#fs_fs_readfile_filename_options_callback
if(fs.existsSync(file_path))
{
var file_content = fs.readFileSync(file_path, 'utf-8');
} else {
var file_content = fs.writeFileSync(file_path, '');
}

Categories

Resources