How to merge two csv files rows in node js - node.js

I have 2 csv files which have different different data but having a same header
eg. FILE 1 data is
"CODE","NAME","SUB_USER","SCORE"
"01","TEST","1","5"
"01","TEST","2","6"
other file FILE2 have data like this
"CODE","NAME","SUB_USER","SCORE"
"02","TEST2","3","5"
"02","TEST2","4","6"
so i want to merge both file create FILE3 output like this
"CODE","NAME","SUB_USER","SCORE"
"01","TEST","1","5"
"01","TEST","2","6"
"02","TEST2","3","5"
"02","TEST2","4","6"
I have tried below code
var express = require('express');
var router = express.Router();
var fs = require('fs');
var parse = require('csv-parse');
var async = require('async');
var csv = require("fast-csv");
var file1 = appRoot + '\\csvFiles\\details1.csv';
var file2 = appRoot + '\\csvFiles\\details2.csv';
var stream = fs.createReadStream(file1);
var stream2 = fs.createReadStream(file2);
var fileData1 = [],
fileData2 = [];
csv
.fromStream(stream)
.on("data", function(data) {
fileData1.push(data);
})
.on("end", function() {
console.log("done");
});
csv
.fromStream(stream2)
.on("data", function(data) {
fileData2.push(data);
})
.on("end", function() {
console.log("done");
});
var fileData3 = fileData1.concat(fileData2);
csv.writeToPath("outputfile.csv", fileData3).on("finish", function() {
console.log("END");
});
But not working don't know why?? Please help me
///**********************************************************************//
Thax for help but i got new problem here
After some changes above code start working
var file1 = appRoot + '\\csvFiles\\details1.csv';
var file2 = appRoot + '\\csvFiles\\idetails2.csv';
var stream = fs.createReadStream(file1);
var stream2 = fs.createReadStream(file2);
var fileData1 = [],
fileData2 = [],
i = 0;
csv.fromStream(stream).on("data", function(data) {
fileData1.push(data);
}).on("end", function() {
csv.fromStream(stream2).on("data", function(data) {
if (i != 0) {
fileData2.push(data);
}
i++;
}).on("end", function() {
console.log("done");
var fileData3 = fileData1.concat(fileData2);
csv.writeToPath("outputfile.csv", fileData3).on("finish", function() {
res.send('Done merge');
});
});
});
But problem is that what if my number of file increase then how i will handle that thing

The biggest problem here is a quite common one. You do async tasks but you don't wait for them to finish before you are using their result.
You concat the file data before the "end" callback for each tasks was called.
The solution is to wait for every callback to be called and THEN working with the data.
I created a small example using Promises
const file1 = 'one.csv';
const file2 = 'two.csv';
const stream = fs.createReadStream(file1);
const stream2 = fs.createReadStream(file2);
const fileData1 = [];
const fileData2 = [];
const file1Promise = new Promise((resolve) => {
csv
.parseFile(file1, {headers: true})
.on('data', function(data) {
fileData1.push(data);
})
.on('end', function() {
console.log('done');
resolve();
});
});
const file2Promise = new Promise((resolve) => {
csv
.parseFile(file2, {headers: true})
.on('data', function(data) {
fileData2.push(data);
})
.on('end', function() {
console.log('done');
resolve();
});
});
Promise.all([
file1Promise,
file2Promise,
])
.then(() => {
const fileData3 = fileData1.concat(fileData2);
console.log(fileData3);
const csvStream = csv.format({headers: true});
const writableStream = fs.createWriteStream('outputfile.csv');
writableStream.on('finish', function() {
console.log('DONE!');
});
csvStream.pipe(writableStream);
fileData3.forEach((data) => {
csvStream.write(data);
});
csvStream.end();
});
I created a function with which you can easily merge multiple files:
function concatCSVAndOutput(csvFilePaths, outputFilePath) {
const promises = csvFilePaths.map((path) => {
return new Promise((resolve) => {
const dataArray = [];
return csv
.parseFile(path, {headers: true})
.on('data', function(data) {
dataArray.push(data);
})
.on('end', function() {
resolve(dataArray);
});
});
});
return Promise.all(promises)
.then((results) => {
const csvStream = csv.format({headers: true});
const writableStream = fs.createWriteStream(outputFilePath);
writableStream.on('finish', function() {
console.log('DONE!');
});
csvStream.pipe(writableStream);
results.forEach((result) => {
result.forEach((data) => {
csvStream.write(data);
});
});
csvStream.end();
});
}
example usage
concatCSVAndOutput(['one.csv', 'two.csv'], 'outputfile.csv')
.then(() => ...doStuff);

Related

How can I use Readable() constructor to read from a text file and write it in a Writable() constructor?

I am trying to read from a text file using new Readable() constructor,but I don't know how to make the code receive it as a file path. I would like the result to be displayed in the console using new Writable() constructor.
const fs = require('fs');
const {Readable} = require('stream');
const {Writable} = require('stream');
const userData = __dirname + '/files/data.txt';
const rStream = new Readable({
read() {}
});
const wStream = new Writable({
write(chunk, encoding, callback) {
console.log("Readable data: ", chunk.toString());
callback();
}
});
rStream.pipe(wStream);
rStream.push(userData);
rStream.on('close', () =>
wStream.end());
wStream.on('close', () =>
console.log('No more data in file...')
);
rStream.on('error', (err) =>
console.log('Readable error!', err.message)
);
wStream.on('error', (err) =>
console.log('Writable error!', err.message)
);
rStream.destroy();

how to work with response object in nodejs stream, exceljs and worker thread

I am using worker thread and stream at same time in node JS project. At initial I was not able to pass res object through main process to worker thread. I saw many stackoverflow question and solution and wrote a solution which works great. I created a Readable stream in main thread and writable stream in worker thread. while doing this, I have done a huge calculation from more than 10 table and export data which takes nearly 1 minutes for processing.
code:
router.get("/downloadAll", (req, res) => {
new Promise((resolve, reject) => {
const promise = [];
promise.push(Dashboard.DUser());
promise.push(Dashboard.DDUser());
promise.push(Dashboard.DDLUser());
promise.push(Dashboard.Din());
promise.push(Dashboard.Str());
promise.push(Dashboard.R());
promise.push(Dashboard.Q());
Promise.all(promise).catch(err => err)
.then(results => {
const worker = new Worker(`${process.cwd()}/src/route/modules/dashboard/worker.js`, {
workerData: { results }
});
const fileHeaders = [
{
name: "Content-Type",
value: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
}
];
res.setHeader("Content-Disposition", `attachment; filename="Stream.xlsx`);
fileHeaders.forEach(header => res.setHeader(header.name, header.value));
const readStream = new Readable({
read() {}
});
readStream.pipe(res);
worker.on("message", message => {
readStream.push(message);
});
worker.on("exit", code => {
console.log("exit", code);
resolve(true);
//if (code !== 0) reject(new Error(`stopped with ${code} exit code`));
});
});
})
.then(() => res.end())
.catch(err => console.log(err));
});
WORKER THREAD:
const { workerData, parentPort } = require("worker_threads");
const { Writable } = require("stream");
const Excel = require("exceljs");
const writableStream = new Writable();
// writableStream.on("message", () => {});
writableStream._write = (chunk, encoding, next) => {
parentPort.postMessage(chunk);
next();
};
const createWorkbook = () => {
const workbook = new Excel.stream.xlsx.WorkbookWriter({
stream: writableStream, // stream to server response
useStyles: true // not sure about this one, check with it turned off.
});
workbook.title = "Serious";
workbook.creator = "SS";
workbook.created = new Date();
return workbook;
};
const createSheet = workbook => {
workerData.results.forEach((result, index) => {
const worksheet = workbook.addWorksheet(result.title, {
properties: { outlineLevelCol: 1 }
});
worksheet.columns = Object.keys(result.data[0]).map(item => {
return { header: item, key: item };
});
result.data.forEach(row => worksheet.addRow(row).commit);
});
};
const workbook = createWorkbook();
createSheet(workbook);
workbook.commit();
The above code works fine and is fast for small calculation. when I have huge computation it is showing processing for 1 minutes and finish processing and download the xls file. so i updated the code to:
router.get("/downloadAll", (req, res) => {
const worker = new Worker(`${process.cwd()}/src/worker/worker.js`);
const fileHeaders = [
{
name: "Content-Type",
value: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
}
];
const today = new Date();
res.setHeader(
"Content-Disposition",
`attachment; filename=Q-${today.getFullYear()}${String(today.getMonth() + 1).padStart(2, "0")}${String(
today.getDate()
).padStart(2, "0")}.xlsx`
);
fileHeaders.forEach(header => res.setHeader(header.name, header.value));
const readStream = new Readable({
read() {}
});
readStream.pipe(res);
worker.on("message", message => {
readStream.push(message);
});
worker.on("exit", code => {
console.log("exit", code);
res.end();
//if (code !== 0) reject(new Error(`stopped with ${code} exit code`));
});
});
and worker thread code:
const { workerData, parentPort } = require("worker_threads");
const { Writable } = require("stream");
const Excel = require("exceljs");
const { resolve } = require("path");
const db = require(`${process.cwd()}/src/modules/db.module`);
const Dashboard = require(`${process.cwd()}/src/route/modules/dashboard.model`);
const promise = [];
promise.push(Dashboard.DUser());
promise.push(Dashboard.DDUser());
promise.push(Dashboard.DDLUser());
promise.push(Dashboard.Din());
promise.push(Dashboard.Str());
promise.push(Dashboard.R());
promise.push(Dashboard.Q());
Promise.all(promise).catch(err => err)
.then(results => { const writableStream = new Writable();
// writableStream.on("message", () => {});
writableStream._write = (chunk, encoding, next) => {
console.log(chunk.toString());
parentPort.postMessage(chunk);
next();
};
const createWorkbook = () => {
const workbook = new Excel.stream.xlsx.WorkbookWriter({
stream: writableStream, // stream to server response
useStyles: true // not sure about this one, check with it turned off.
});
workbook.creator = "ss";
workbook.created = new Date();
return workbook;
};
const createSheet = workbook => {
results.forEach((result, index) => {
// console.log(result);
const worksheet = workbook.addWorksheet(result.title, {
properties: { outlineLevelCol: 1 }
});
worksheet.columns = Object.keys(result.data[0]).map(item => {
return { header: item, key: item };
});
result.data.forEach(row => worksheet.addRow(row).commit);
});
};
The above code doesnot work correctly. I can get the data from callback from promise but when its downloading its shows 300kb , 200b,1byte and ends to 0 but it does not download.
if I try to insert the promise inside createsheet then i am getting error:
Error [ERR_UNHANDLED_ERROR]: Unhandled error. ({ message: 'queue closed', code: 'QUEUECLOSED', data: undefined })
code:
const createSheet = workbook => {
let promise = [];
/**
* get count of all the user list
*/
promise.push(Dashboard.DDPro());
Promise.all(promise)
.then(results => {
results.forEach((result, index) => {
console.log(result);
const worksheet = workbook.addWorksheet(result.title, {
properties: { outlineLevelCol: 1 }
});
worksheet.columns = Object.keys(result.data[0]).map(item => {
return { header: item, key: item };
});
result.data.forEach(row => worksheet.addRow(row).commit);
});
})
.catch(err => console.log(err));
};
can any body helps me solve the problem.

Node.js hangs on HTTP get when download files

I want to download a series of ts files, but every time I run this code, it will be stuck in the download process of a file without any error message.
However, if you put the url in the program in the address bar of the browser, or use a tool like wget, you can still download it.
const puppeteer = require('puppeteer');
var https = require('https');
var fs = require('fs');
async function doRequest(url) {
return new Promise(function (resolve) {
var req = https.get(url, function (response) {
resolve(response);
});
req.end('error', function(e) {
sleep(3000).then(() => {
console.log('re try to get ts ...'+e);
doRequest(url); })
});
req.on('error', function(e) {
sleep(3000).then(() => {
console.log('re try to get ts ...'+e);
doRequest(url); })
});
});
}
(async() => {
for(let i = 21; i<100; i++)
{
var ts_url = 'https://hls2.videos.sproutvideo.com/1e7c8a8ff0518509452c7eb2e75a2a1f/e84883ff69cb66752bd6783cdbaa35fb/video/720_000'+i+'.ts?Policy=eyJTdGF0ZW1lbnQiOlt7IlJlc291cmNlIjoiaHR0cHM6Ly9obHMyLnZpZGVvcy5zcHJvdXR2aWRlby5jb20vMWU3YzhhOGZmMDUxODUwOTQ1MmM3ZWIyZTc1YTJhMWYvZTg0ODgzZmY2OWNiNjY3NTJiZDY3ODNjZGJhYTM1ZmIvKi50cz9zZXNzaW9uSUQ9MDZkN2ZhOWMtMDgxOS00Y2YwLTk0M2QtNzA2MGQzOGY2N2RkIiwiQ29uZGl0aW9uIjp7IkRhdGVMZXNzVGhhbiI6eyJBV1M6RXBvY2hUaW1lIjoxNTQ2NzY3NjY4fX19XX0_&Signature=DTCQWVIdInCe2YIf-fxD4RDEHOXGUDK2pUwxV0cKPi0m~WwlLYIEFSmQkAbK-oV-uLU93E1O2TGizvrMDp6voFVnm-jLaOur1JRlJDBCP7T8KEYrkkU3Y3grZAKHmi0gQiVpVIKRgo7gnDKwMZ1NjosQPbaf1XDMpuHxAyKfPGgIRLpSEp4BZ1dqcfzs-YyYQzNaK-a3tYONmpyID3bZnF8sn2pMZonArCz24BQL0wEfXeS3HqxwVv85z641kKxQBGd~8lG88qUTpJCvqWmIZhikzWjGQPY~6ezgJMKhjJQIoPMVGZehT~NcAzPwXo84kd5ksaOdbh4paHsUe1096A__&Key-Pair-Id=APKAIB5DGCGAQJ4GGIUQ&sessionID=06d7fa9c-0819-4cf0-943d-7060d38f67dd';
await console.log('downloading '+i);
var file_ts_path = fs.createWriteStream(i+'.ts');
let responseRes = await doRequest(ts_url);
await responseRes.pipe(file_ts_path);
}
})();
const puppeteer = require('puppeteer');
var https = require('https');
var fs = require('fs');
async function doRequest(url) {
return new Promise(function (resolve) {
var req = https.get(url, function (response) {
resolve(response);
});
req.end('error', function(e) {
sleep(3000).then(() => {
console.log('re try to get ts ...'+e);
doRequest(url); })
});
req.on('error', function(e) {
sleep(3000).then(() => {
console.log('re try to get ts ...'+e);
doRequest(url); })
});
});
}
(async() => {
for(let i = 21; i<100; i++)
{
var ts_url = 'https://hls2.videos.sproutvideo.com/1e7c8a8ff0518509452c7eb2e75a2a1f/e84883ff69cb66752bd6783cdbaa35fb/video/720_000'+i+'.ts?Policy=eyJTdGF0ZW1lbnQiOlt7IlJlc291cmNlIjoiaHR0cHM6Ly9obHMyLnZpZGVvcy5zcHJvdXR2aWRlby5jb20vMWU3YzhhOGZmMDUxODUwOTQ1MmM3ZWIyZTc1YTJhMWYvZTg0ODgzZmY2OWNiNjY3NTJiZDY3ODNjZGJhYTM1ZmIvKi50cz9zZXNzaW9uSUQ9MDZkN2ZhOWMtMDgxOS00Y2YwLTk0M2QtNzA2MGQzOGY2N2RkIiwiQ29uZGl0aW9uIjp7IkRhdGVMZXNzVGhhbiI6eyJBV1M6RXBvY2hUaW1lIjoxNTQ2NzY3NjY4fX19XX0_&Signature=DTCQWVIdInCe2YIf-fxD4RDEHOXGUDK2pUwxV0cKPi0m~WwlLYIEFSmQkAbK-oV-uLU93E1O2TGizvrMDp6voFVnm-jLaOur1JRlJDBCP7T8KEYrkkU3Y3grZAKHmi0gQiVpVIKRgo7gnDKwMZ1NjosQPbaf1XDMpuHxAyKfPGgIRLpSEp4BZ1dqcfzs-YyYQzNaK-a3tYONmpyID3bZnF8sn2pMZonArCz24BQL0wEfXeS3HqxwVv85z641kKxQBGd~8lG88qUTpJCvqWmIZhikzWjGQPY~6ezgJMKhjJQIoPMVGZehT~NcAzPwXo84kd5ksaOdbh4paHsUe1096A__&Key-Pair-Id=APKAIB5DGCGAQJ4GGIUQ&sessionID=06d7fa9c-0819-4cf0-943d-7060d38f67dd';
await console.log('downloading '+i);
var file_ts_path = fs.createWriteStream(i+'.ts');
let responseRes = await doRequest(ts_url);
await responseRes.pipe(file_ts_path);
}
})();
const puppeteer = require('puppeteer');
var https = require('https');
var fs = require('fs');
async function doRequest(url) {
return new Promise(function (resolve) {
var req = https.get(url, function (response) {
resolve(response);
});
req.end('error', function(e) {
sleep(3000).then(() => {
console.log('re try to get ts ...'+e);
doRequest(url); })
});
req.on('error', function(e) {
sleep(3000).then(() => {
console.log('re try to get ts ...'+e);
doRequest(url); })
});
});
}
(async() => {
for(let i = 21; i<100; i++)
{
var ts_url = 'https://hls2.videos.sproutvideo.com/1e7c8a8ff0518509452c7eb2e75a2a1f/e84883ff69cb66752bd6783cdbaa35fb/video/720_000'+i+'.ts?Policy=eyJTdGF0ZW1lbnQiOlt7IlJlc291cmNlIjoiaHR0cHM6Ly9obHMyLnZpZGVvcy5zcHJvdXR2aWRlby5jb20vMWU3YzhhOGZmMDUxODUwOTQ1MmM3ZWIyZTc1YTJhMWYvZTg0ODgzZmY2OWNiNjY3NTJiZDY3ODNjZGJhYTM1ZmIvKi50cz9zZXNzaW9uSUQ9MmFmN2JkNzEtODc3Mi00OThmLThjNzQtN2Y5NTQ3ZTgxYjA2IiwiQ29uZGl0aW9uIjp7IkRhdGVMZXNzVGhhbiI6eyJBV1M6RXBvY2hUaW1lIjoxNTQ2NzEzNzU4fX19XX0_&Signature=hFOZlf5Iqf7k-LqVms1FT4LKoEM8psMVkCsdjoHGhKztNTzROyGgfHg34RYr3ezffQaQV6drXBuID1NMypQhwSXgJ-ZRAoGC3KnKtrfm9bSpK2Wq97sZf97D5PbBn7wNaJhmfvbztym-cRknztepOqM2v~KvCz6~esS99TOsWbtQFBZWLPacp5MV3v5eZ4wh2WJXX1jDqI1XmpZ0jyU2oJCXOgVbvU1aF86E7duvniDrbhmS1R00~tWTAETBbmBSubDw-7fGq7XzeZcFRfXbdwb0a9KwsAGh54lj1UBUMsDzEtH8vI8r9aC~MnFIRub1KxsFSOzUlRLYRp4GsPJQiQ__&Key-Pair-Id=APKAIB5DGCGAQJ4GGIUQ&sessionID=2af7bd71-8772-498f-8c74-7f9547e81b06';
await console.log('downloading '+i);
var file_ts_path = fs.createWriteStream(i+'.ts');
let responseRes = await doRequest(ts_url);
await responseRes.pipe(file_ts_path);
}
})();
You need to download a file, write it to stream, and then pipe it.
https://nodejs.org/api/https.html#https_https_get_url_options_callback
https://nodejs.org/api/fs.html#fs_fs_createwritestream_path_options
var https = require('https');
var fs = require('fs');
function doRequest(url, dest) {
return new Promise(function (resolve) {
https.get(url, res => {
let data = '';
res.on('data', (buffer) => {
data += buffer; // save downloaded data
});
res.on('end', () => {
var stream = fs.createWriteStream(dest);
stream.write(data, 'binary');
stream.on('finish', () => {
resolve('File Saved !');
});
res.pipe(stream);
});
}).on('error', function (e) {
reject('re try to get ts ...' + e);
});
});
}
for (let i = 21; i < 100; i++) {
var ts_url =
'https://hls2.videos.sproutvideo.com/1e7c8a8ff0518509452c7eb2e75a2a1f/e84883ff69cb66752bd6783cdbaa35fb/video/720_000' +
i +
'.ts?Policy=eyJTdGF0ZW1lbnQiOlt7IlJlc291cmNlIjoiaHR0cHM6Ly9obHMyLnZpZGVvcy5zcHJvdXR2aWRlby5jb20vMWU3YzhhOGZmMDUxODUwOTQ1MmM3ZWIyZTc1YTJhMWYvZTg0ODgzZmY2OWNiNjY3NTJiZDY3ODNjZGJhYTM1ZmIvKi50cz9zZXNzaW9uSUQ9MDZkN2ZhOWMtMDgxOS00Y2YwLTk0M2QtNzA2MGQzOGY2N2RkIiwiQ29uZGl0aW9uIjp7IkRhdGVMZXNzVGhhbiI6eyJBV1M6RXBvY2hUaW1lIjoxNTQ2NzY3NjY4fX19XX0_&Signature=DTCQWVIdInCe2YIf-fxD4RDEHOXGUDK2pUwxV0cKPi0m~WwlLYIEFSmQkAbK-oV-uLU93E1O2TGizvrMDp6voFVnm-jLaOur1JRlJDBCP7T8KEYrkkU3Y3grZAKHmi0gQiVpVIKRgo7gnDKwMZ1NjosQPbaf1XDMpuHxAyKfPGgIRLpSEp4BZ1dqcfzs-YyYQzNaK-a3tYONmpyID3bZnF8sn2pMZonArCz24BQL0wEfXeS3HqxwVv85z641kKxQBGd~8lG88qUTpJCvqWmIZhikzWjGQPY~6ezgJMKhjJQIoPMVGZehT~NcAzPwXo84kd5ksaOdbh4paHsUe1096A__&Key-Pair-Id=APKAIB5DGCGAQJ4GGIUQ&sessionID=06d7fa9c-0819-4cf0-943d-7060d38f67dd';
doRequest(ts_url, i + '.ts')
.then(console.log)
.catch(console.log);
}

Streaming image data from node server results in corrupted file (gridfs-stream)

I decided to post this after extensive searching here (1, 2, 3 ) and here (1, 2) and many, many other related posts. I am loosing hope, but will not give up that easily :)
I'm using multer to upload a PNG image to mongo database:
const storage = new GridFsStorage({
url: 'mongodb://my_database:thisIsfake#hostName/my_database',
file: (req, file) => {
return new Promise((resolve, reject) => {
crypto.randomBytes(16, (err, buf) => { // generating unique names to avoid duplicates
if (err) {
return reject(err);
}
const filename = buf.toString('hex') + path.extname(file.originalname);
const fileInfo = {
filename: filename,
bucketName: 'media',
metadata : {
clientId : req.body.client_id // added metadata to have a reference to the client to whom the image belongs
}
};
resolve(fileInfo);
});
});
}
});
const upload = multer({storage}).single('image');
Then I create a stream and pipe it to response:
loader: function (req, res) {
var conn = mongoose.createConnection('mongodb://my_database:thisIsfake#hostName/my_database');
conn.once('open', function () {
var gfs = Grid(conn.db, mongoose.mongo);
gfs.collection('media');
gfs.files.find({ metadata : {clientId : req.body.id}}).toArray(
(err, files) => {
if (err) throw err;
if (files) {
const readStream = gfs.createReadStream(files[0].filename); //testing only with the first file in the array
console.log(readStream);
res.set('Content-Type', files[0].contentType)
readStream.pipe(res);
}
});
});
}
Postman POST request to end point results in response body being displayed as an image file:
In the front end I pass the response in a File object, read it and save the result in a src attribute of img:
findAfile(){
let Data = {
id: this.$store.state.StorePatient._id,
};
console.log(this.$store.state.StorePatient._id);
visitAxios.post('http://localhost:3000/client/visits/findfile', Data )
.then(res => {
const reader = new FileReader();
let file = new File([res.data],"image.png", {type: "image/png"});
console.log('this is file: ',file);
reader.readAsDataURL(file); // encode a string
reader.onload = function() {
const img = new Image();
img.src = reader.result;
document.getElementById('imgContainer').appendChild(img);
};
})
.catch( err => console.error(err));
}
My File object is similar to the one I get when using input field only bigger:
This is original file:
When inspecting element I see this:
Looks like data URI is where it should be, but it's different from the original image on file input:
Again, when I want to display it through input element:
onFileSelected(event){
this.file = event.target.files[0];
this.fileName = event.target.files[0].name;
const reader = new FileReader();
console.log(this.file);
reader.onload = function() {
const img = new Image();
img.src = reader.result;
document.getElementById('imageContainer').appendChild(img);
};
reader.readAsDataURL(this.file);
}
I get this:
But when reading it from the response, it is corrupted:
Postman gets it right, so there must be something wrong with my front-end code, right? How do I pass this gfs stream to my html?
I managed to make a POST request to fetch an image from MongoDB and save it in the server dir:
const readStream = gfs.createReadStream(files[0].filename);
const wstream = fs.createWriteStream(path.join(__dirname,"uploads", "fileToGet.jpg"));
readStream.pipe(wstream);
Then, I just made a simple GET request by adding an absolute path to the and finally delete the file after successful response:
app.get('/image', function (req, res) {
var file = path.join(dir, 'fileToGet.jpg');
if (file.indexOf(dir + path.sep) !== 0) {
return res.status(403).end('Forbidden');
}
var type = mime[path.extname(file).slice(1)] || 'text/plain';
var s = fs.createReadStream(file);
s.on('open', function () {
res.set('Content-Type', type);
s.pipe(res);
});
s.on('end', function () {
fs.unlink(file, ()=>{
console.log("file deleted");
})
});
s.on('error', function () {
res.set('Content-Type', 'text/plain');
res.status(404).end('Not found');
});

How to convert properties file to xml node.js

I have properties File and I want to convert it to XML by using node.js.I don't know how can I convert, please help me
const builder = require('xmlbuilder');
const fs = require('fs');
const path = require('path');
const PROPS_FILE = //PROPS_FILE_PATH;
const XML_FILE = //XML_FILE_PATH;
let xml = builder.create('resources');
let readFromPropsFile = function(){
let promise = new Promise(function(resolve, reject){
console.log(PROPS_FILE);
const readline = require('readline');
const rl = readline.createInterface({
input: fs.createReadStream(path.resolve(__dirname,PROPS_FILE))
});
rl.on('line', (line) => {
let keyValuePair = line.split('=');
// converting key valur to XML
convertToXML(keyValuePair[0], keyValuePair[1]);
});
rl.on('error', function(e) {
console.log(e);
reject(e);
// something went wrong
});
rl.on('close', function(line){
console.log(`done reading file ${PROPS_FILE}.`);
resolve();
})
});
return promise;
};
let convertToXML= function(key, value){
xml.ele('string', {'name': `${key}`}, `${value}`);
};
let writeInToXMLFile = function(){
let promise = new Promise(function(resolve, reject){
fs.writeFile(path.resolve(__dirname,XML_FILE) , xml, function (error) {
if (error) {
console.error(error);
reject(new Error(error));
} else {
console.log(`file ${XML_FILE} saved `);
resolve();
}
});
});
return promise;
}
readFromPropsFile()
.then(writeInToXMLFile)
.catch((err)=>{ console.log(err) });

Resources