How to read file in Node? - javascript

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, '');
}

Related

How to create a json file which has name contains slashes >> Uncaught Error: ENOENT: no such file or directory, open './global/sites.json'

I want to create a folder (if folder does not exist) called
alexadata and create a json file under this folder which contains 'data' and named with slashes like global/sites.json , else
just want to create this json file into the alexadata folder. But both
of two status, I have an error Uncaught Error: ENOENT: no such file
or directory, open './global/sites.json' where if(err) return
err; line. If folder does not exist, then it is created but json
file is not created and gives this error. How can I fix this issue?
Please help me. Thank you in advance.
jsToJSON: async (data) => {
try {
let url = await page.url();
const code = await page.evaluate(() => {
return {
code: document.querySelector('#alx-content > div.row-fluid.TopSites.AlexaTool.padding20 > section.page-product-top > div > section > div.Foldering > div.each.current > a').innerText.toLowerCase()
}
});
const fields = ['rank', 'name', 'url', 'last_update'];
const json2csvParser = new Json2csvParser({ fields });
var _path = path.join(__dirname,'alexadata');
if (!fs.existsSync("alexadata")) {
fs.mkdir("alexadata", (err) => {
if (err) return err;
fs.writeFileSync(`./${code.code}/sites.json`, JSON.stringify(data), 'utf-8', (err) => {
if (err) return err;
console.log("Directory and File Saved ");
});
});
} else {
fs.writeFile(path.join(_path, `/${code.code}/sites.json`), JSON.stringify(data), 'utf-8', (err) => {
if (err) return err;
console.log("Directory and File Saved ");
});
}
} catch (error) {
console.log(error)
}
}

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);
});
});

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

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)
})

NodeJS Html-pdf: fs.readfilesync how to async/await

I have a problem with my html-pdf document creation. The problem is that often the code runs to fast to complete the process of pdf-docutment creation. The Processes consists out of building an HTML-String by replacing placeholders in an Html file. Below you see the code what happens afterwards.
Object.keys(setter).forEach(function(element, key, _array) {
var regex = new RegExp(element, "g");
data = data.replace(regex, setter[element])
})
var result = data;
fs.writeFile(mergeFileRes, result, 'utf8', function (err) {
if(err) {
console.log(err);
return;
} else {
let html2 = fs.readFileSync(mergeFileRes, 'utf8');
let options = {
format: 'a4' ,
"directory" : "/tmp",
};
if(html2){
pdf.create(html2, options).toStream(function(err, stream2){
if(err) console.log(err);
stream2.pipe(res);
stream2.on('end', function () {
try{
fs.unlink(mergeFileRes)
console.log(3090, "deleted file");
}
catch (err){
console.log(3090, "Did not delete file");
}
});
});
} else {
}
}
});
My problem is that in many cases the html2 variable is not yet created before the pdf.create process starts. This is probably because the readFileSync takes too long to finish.
I was wondering, how can I fix this. How can I make the pdf.create wait for the readFileSync to finish and the html2 variable to be filled.
You can use fs.readFile to read the file asynchronously and html2 will be available within the callback function.
Object.keys(setter).forEach(function(element, key, _array) {
var regex = new RegExp(element, "g");
data = data.replace(regex, setter[element])
})
var result = data;
fs.writeFile(mergeFileRes, result, 'utf8', function (err) {
if(err) {
console.log(err);
return;
} else {
fs.readFile(mergeFileRes, 'utf8', function(err, html2){
if (err) throw err;
let options = {
format: 'a4' ,
"directory" : "/tmp",
};
pdf.create(html2, options).toStream(function(err, stream2){
if(err) console.log(err);
stream2.pipe(res);
stream2.on('end', function () {
try{
fs.unlink(mergeFileRes)
console.log(3090, "deleted file");
}
catch (err){
console.log(3090, "Did not delete file");
}
});
});
});
}
});

How to check if file exist before appending data into it using nodejs?

I have a case where once user download a file i am deleting it from the directory, Now once new message comes in its still trying to append to the file that does not exist , How can i check if obj.file exist then only append ?
server.js
recordLogs: function (obj) {
var path = './app/records/templogs'
var fileAppend = path + '/'+ obj.file;
console.log('data from recoring', obj.data);
fs.readdir(path, function(err, items) {
items.forEach(function(file){
if(obj.file === file){
fs.appendFile(fileAppend, obj.data, null, 'utf8', function (err) {
if (err) throw err;
});
console.log('filename in records',obj.file);
}
});
});
}

Categories

Resources