I am trying to read a pdf file from fs and send it through email using sendgrid.
My folder structure is like this
/
-src
--controllers
---travelplan.js
-pdf
In the travelplan.js if I do it like this
fs.readFile('pdf/204.pdf', function (err, data) {
if (err) {
console.log("THIS ERROR IS AWESOME", err)
}
})
everything works fine. No problem.
But if read it like this
let pdf_number = 204;
fs.readFile(`pdf/${pdf_number}.pdf`, function (err, data) {
if (err) {
console.log("THIS ERROR IS AWESOME", err)
}
})
This doesn't work. Pdf doesn't send correctly.
Then I tried this
let pdf_number = 204;
var pdf_path = path.join(__dirname, '..', 'pdf',pdf_number);
fs.readFile(pdf_path, function (err, data) {
if (err) {
console.log("THIS ERROR IS AWESOME", err)
}
})
This also doesn't work.
How do I read a pdf file by passing the pdf file name as an argument?
Related
So, I have this code in Unity:
var www = UnityWebRequest.Put(NetworkManager.Instance.data.ConnectionURL + "/upload-schedule", contents);
www.SetRequestHeader("Content-Type", "application/json");
yield return www.SendWebRequest();
if (www.result == UnityWebRequest.Result.ConnectionError)
{
Debug.LogError("There was an error uploading the schedule");
}
else {
string downloadContents = www.downloadHandler.text;
Debug.Log(downloadContents);
}
And then I have this node express application receiving this data:
app.put('/upload-schedule', (req, res) => {
var filePath = "./data/schedule.json";
var data = JSON.stringify(req.body);
// Write file
fs.writeFile(filePath, data, (err) => {
// Dip if an error is found
if (err) {
console.error(err);
return;
}
// Send found data
res.send("Successfuly uploaded file!");
console.log("Successfuly uploaded file!");
});
});
For some reason, this works fine on localhost, but, as soon as I use my web api, req.body always comes out empty. Does anyone know the reason for this and how I can fix it? Thank you
I have been trying to download image file using JS force for node js and able to create a file on local after retrieving data and converting it to base64 format but image if showing "file not supported message" whereas being able to download javascript type of file with correct data.
I am querying the attachment field of knowledge article in salesforce.
Following is my query :
SELECT Body__c, Attachment__Name__s, Attachment__ContentType__s, Attachment__Length__s, Attachment__Body__s, Id, KnowledgeArticleId, Title, UrlName FROM Knowledge__kav
I am sending GET request to Attachment__Body__s field of article.
Following is my node js code:
function createFile(attachmentBody,attachmntContentType,attachmntName){
var req = {
url: attachmentBody,
method: 'GET',
headers: {
"Content-Type": attachmntContentType
}
};
var test = conn.request(req, function(err, resp) {
if (err) {
console.log(err)
} else {
var fileBuffer=Buffer.from(resp, 'binary').toString('base64');
console.log('fileBuffer--- '+ fileBuffer);
fs.writeFile('./downloadedAttachments/'+attachmntName,fileBuffer,'base64', function(err){
if (err) throw err
console.log('File saved.')
})
}
});
}
Please help me with this.
I am successfully able to download the file in the correct format. following is my updated code :
function createFile(knbid,attachmntName,callback) {
var file_here = conn.sobject('Knowledge__kav').record(knbid);
file_here.retrieve(function (err, response) {
if (err) {
return console.error(err);
callback(0)
} else {
var obj = fs.createWriteStream('./downloadedAttachments/'+attachmntName, {defaultEncoding: 'binary'})
//console.log('blob--'+JSON.stringify(file_here.blob('Attachment__Body__s')));
var stream = file_here.blob('Attachment__Body__s').pipe(obj);
stream.on('finish', function (err, result) {
if (err)
console.log('not downloaded'+knbid);
else
console.log('downloaded-'+knbid);
})
}
});
}
I am trying to make a program in Node.js that would anonymize a given path for a word doc for a larger project. I have already unzipped the docx file and I have edited the document.xml file. All I need to do now is recompress it.
I have looked into using Archiver, but the problem is that it is zipping the folder to a .zip, so when you try to convert it to a docx, it is corrupted.
fs.readFile('./extracted_doc/word/document.xml', 'utf8', (err, data) => {
if (err) reject(err);
var name = data.indexOf('<w:t>')
var end = data.indexOf('<\/w:t>')
var result = data.replace(data.slice(name + 5, end), "XXXXXXXXXXXXXXXXXX")
fs.writeFile('./extracted_doc/word/document.xml', result, (err) => {
if (err) reject(err)
//zipping the file back to docx
var output = fs.createWriteStream('./anonymized_submission.docx')
var archive = archiver('zip')
archive.on('error', function (err) {
throw err;
})
archive.pipe(output)
archive.directory("./extracted_doc", "extracted_doc")
archive.finalize()
})
});
Here's a potential solution to your problem, I've tested and it works for me. It will replace the first line with 'XXXX...'.
The main issue with your existing code was it was creating a root directory 'extracted_doc' in the .zip file that contains the doc archive. This is not what Word is expecting. It expects the document structure in the root of the archive.
I've created the zipDirectory function to work around this. The main goal here is to preserve the directory structure of the archive.
const archiver = require("archiver");
const fs = require("fs");
fs.readFile('./extracted_doc/word/document.xml', 'utf8', (err, data) => {
if (err) reject(err);
var name = data.indexOf('<w:t>');
var end = data.indexOf('<\/w:t>');
var result = data.replace(data.slice(name + 5, end), "XXXXXXXXXXXXXXXXXX")
fs.writeFile('./extracted_doc/word/document.xml', result, (err) => {
if (err) reject(err);
zipDirectory('./extracted_doc/', './anonymized_submission.docx');
})
});
function zipDirectory(inputDir, outputFile) {
let archive = archiver('zip');
archive.on('error', function (err) {
throw err;
})
let output = fs.createWriteStream(outputFile);
archive.pipe(output);
/* Ok, so we don't want a root name of <input_dir>, this is our workaround. */
archive.directory(inputDir, '../');
archive.finalize();
}
I want to save an image to my node.js folder.
Save function:
function saveBrochure(brochure, image, file) {
return uploadBrochure(file).then(
data => {
uploadImage(image);
return brochureModel.addBrochure(brochure);
},
error => {
return error;
}
);
}
upload function:
function uploadImage(image) {
var path = 'my-path/' + image.filename;
fs.writeFile(path, image, function(err) {
if (err) {
console.log(err);
}
});
}
My image object looks like this
destination:"path"
encoding:"7bit"
fieldname:"image"
filename:"filename"
mimetype:"image/png"
originalname:"filename"
path:"path/filename.png"
size:155217
After the upload, I can see that a corrupted image file has been added to my project.
Any idea what I'm doing wrong?
I want to save files that I am getting from another server on my server but the problem is when I am calling createWriteStream it giving me the error :
no such file or directory, open
E:\pathtoproject\myproject\public\profile_14454.jpg
Here is my code which is in E:\pathtoproject\myproject\modules\dowload.js :
request.head(infos.profile_pic, function(err, res, body) {
const completeFileName = '../public/profile_14454.' + res.headers['content-type'].split('/')[1];
var imageStream = fs.createWriteStream(completeFileName);
imageStream.on('open', function(fd) {
console.log("File open");
request(infos.profile_pic).pipe(imageStream).on('close', function(body) {
consoleLog('Profile pic saved');
console.log('This is the content of body');
console.log(body);
connection.query('UPDATE user set photo=? where id=?', [completeFileName, lastID], function(err, result, fields) {
if (err) {
consoleLog('Error while update the profile pic');
}
});
})
});
});
When I removed the directory ../public/ and leave only the name of the file
profile_14454.' + res.headers['content-type'].split('/')[1] , it worked but the file was saved in the root directory of the project (E:\pathtoproject\myproject\).
What's wrong in what I am doing? How can I have the file saved under public directory?
I am using nodeJS 8.9.4
I tried with my small code .
var fs = require("fs");
var data = 'Simply Easy Learning';
// Create a writable stream
var writerStream = fs.createWriteStream('./airo/output.txt');
// Write the data to stream with encoding to be utf8
writerStream.write(data,'UTF8');
// Mark the end of file
writerStream.end();
// Handle stream events --> finish, and error
writerStream.on('finish', function() {
console.log("Write completed.");
});
writerStream.on('error', function(err){
console.log(err.stack);
});
console.log("Program Ended");
My code is in this path E:\syed ayesha\nodejs\nodejs now I want to store my file in airo folder which is in this path. So I used one dot for storing. Hope this helps.