const xml2js = require('xml2js');
const fs = require('fs');
fs.readFile('https://www.tcmb.gov.tr/kurlar/today.xml', (err, data) => {
if(err) console.log(err);
var data = data.toString().replace("\ufeff", "");
xml2js.parseStringPromise(data, (err, res) => {
if(err){
console.log(err);
} else {
console.log(res);
}
});
});
This is my code in nodejs I try to get data on a https link with xml2js first by using the way it says in the npm page pf xml2js it gives some error and when I chechk on web I find solution of using with fs but still geting this error
I know the directory exists because if you go to link used in code it shows something but in code just gives error if someone can help I will be very happy
fs can only access file in your system, you should request the URL using http/https or even better try axios
const axios = require('axios')
axios.get('https://www.tcmb.gov.tr/kurlar/today.xml').then((response) => {
const data = response.data
xml2js.parseString(data, (err, res) => {
if(err){
console.log(err);
} else {
console.log(res);
}
})
})
Related
I'm currently stuck trying to retrieve a file from file system in order to send it through api to the client. For my backend I'm using express js
I'm using fs library and currently I'm trying to do it with readFile function, but I want to do it without specifying the file name or just the file extension because it will depend from file file will be uploaded from client.
What I tried until now (unsuccessfully) is shown below:
router.get("/info/pic", async (req, res) => {
const file = await fs.readFile("./images/profile/me.*", (err, data) => {
if (err) {
console.log(err); // Error: ENOENT: no such file or directory, open './images/profile/me.*'
return;
}
console.log(data);
});
});
const file = await fs.readFile("./images/profile/*.*", (err, data) => {
if (err) {
console.log(err); // Error: ENOENT: no such file or directory, open './images/profile/*.*'
return;
}
console.log(data);
});
const file = await fs.readFile("./images/profile/*", (err, data) => {
if (err) {
console.log(err); // Error: ENOENT: no such file or directory, open './images/profile/*'
return;
}
console.log(data);
});
If I specify the file name everything works fine, like: fs.readFile("./images/profile/me.jpg". but as I said, I don't know for sure the right extension of that file.
Important info: In that directory there will be only one file!
Please help me!
Thank you in advance!
If there is only one file in the directory, the following loop will have only one iteration:
for await (const file of fs.opendirSync("./images/profile")) {
var image = fs.readFileSync("./images/profile/" + file.name);
...
}
const fs = require('fs');
fs.readdir('./images/profile', function (err, files) {
//handling error
if (err) {
return console.log('err);
}
files.forEach(function (file) {
// Do whatever you want to do with the file
});
});
I have stored the file after uploading it to the downloads folder in my project directory.
I want to download that saved file from the frontend.
When I click on the download button, it doesn't fetch the file.
And when I go to http://localhost:5000/download on the express app, I got this error message
Error: Can't set headers after they are sent.
Express Server Code:
app.get('/download', (req, res) => {
res.send('file downloaded')
const file = './downloads/output.yml';
res.download(file, 'openapi.yml', (err) => {
if (err) {
console.log(err)
} else {
console.log('file downloaded')
}
});
});
Frontend App code:
HTML:
<button class="download-btn">download</button>
Script:
const handleDownload = async () => {
const res = await fetch("https://cors-anywhere.herokuapp.com/http://localhost:5000/download");
const blob = await res.blob();
download(blob, 'output.yml');
}
downloadBtn.addEventListener('click', handleDownload);
Folder Structure:
Update:
Server.js
const uploadFiles = async (req, res) => {
const file = await req.files[0];
console.log(file)
postmanCollection = file.path;
outputFile = `downloads/${file.filename}.yml`
convertCollection();
res.json({ message: "Successfully uploaded files" });
}
app.post("/upload_files", upload.array("files"), uploadFiles);
Anyone please help me with this.
You are already using res.send ,which sends the response headers back to client ,which ends the request response cycle ,and when you try to do res.download it throws error. Use instead
app.get('/download', (req, res) => {
const file = './downloads/output.yml';
res.download(file, 'openapi.yml', (err) => {
if (err) {
console.log(err)
} else {
console.log('file downloaded')
}
});
});
res.send('file downloaded')--->remove this line
You need to update your js code as well
const handleDownload = async () => {
const res = await fetch("https://cors-anywhere.herokuapp.com/download"); //http://localhost:5000--->this is not required
const blob = await res.blob();
download(blob, 'output.yml');
}
downloadBtn.addEventListener('click', handleDownload);
I am creating an endpoint that serves a file generated dynamically. I have written a controller which generates the file after certain operation based on request param fileId.
I am throwing some errors if anything goes wrong while file generation or it is an invalid request. I have used Promise.reject() for throwing error and on successful file generation returning the response {fileName, filePath} as Promise from the controller.
import express from 'express'
import downloadFile from '../controller/file.controller'
const router = express.Router()
router.post('/file/download/:fileId', (req, res) => {
downloadFile(req.fileId).then((fileResp) => {
res.download(fileResp.filePath, fileResp.fileName, function (error) {
if (error) {
console.log('Downloading error')
} else {
console.log('Downloading success')
}
})
}).catch((error) => {
res.status(error.status).json({message: error.message})
})
})
I have observed that file is being served on requesting endpoint but it will be empty of size zero bytes.
I have tried the same thing without Promise which works well. In this approach, I have changed my errors from Promise.reject() to throw error and response from Promise to an object
import express from 'express'
import downloadFile from '../controller/file.controller'
const router = express.Router()
router.post('/file/download/:fileId', (req, res) => {
const fileResp = downloadFile(req.fileId)
res.download(fileResp.filePath, fileResp.fileName, function (error) {
if (error) {
console.log('Downloading error')
} else {
console.log('Downloading success')
}
})
})
I am unable to find the issue in the 1st approach. Is it Promise which is causing the issue or I am doing something wrong?
Client code:
var data = new FormData();
data.append(fileName, blob, 'test.html');
fetch('http://localhost:3000/', {
method: 'POST',
headers: {
},
body: data
}).then(
response => {
console.log(response)
}
).then(
success => {
console.log(success)
}
).catch(
error => {
console.log(error)
}
);
Server code:
router.post('/', urlencodedParser, function(req, res, next) {
const body = req.body;
console.log(body);
res.send(`You sent: ${body} to Express`);
});
I am sending a blob in the body of a post request. When I send it to the server I want the server to download the file from the body of the request. How can i download this file? Or is there a simpler way to upload from client?
If you can utilize an NPM package formidable, there appears to be a solution at: https://www.w3schools.com/nodejs/nodejs_uploadfiles.asp
Once you have the file received, you can use the fs module to save and store in server
May it can solve your problem.
const fs = require('fs');
let directory = '/temp/data'; // where you want to save data file
router.post('/', urlencodedParser, function(req, res, next) {
const body = req.body;
console.log(body);
fs.writeFile(directory, body, function(err) {
if(err) {
return console.log(err);
}
console.log("File has been saved");
});
res.send(`You sent: ${body} to Express`);
});
This solved my answer - https://attacomsian.com/blog/uploading-files-nodejs-express, which basically uses a middleware to do the upload.
This was basically like:
const x = 6;
console.log(x);
Error: value is f'd up
const x = 6;
magic.valueParse(x);
console.log(x);
6
Also, i would like to point out how bodyParser cannot be used for multipart data. It is mentioned on the official docs, but even responses I get seem to point to bodyParser. So I thought I'd re-iterate that.
I need your help.
I want to get the public IP address of my Beaglebone via ifconfig.me.
If I have an existing internet connection it works fine. If I don't have an internet connection the request should be aborted.
Here is my code:
function publicIP_www(callback){
try{
exec('curl ifconfig.me',{timeout:3000}, function(error, stdout, stderr){
callback(stdout); });
}
catch (err){
callback("000.000.000.000");
}
}
The returned IP address is then displayed on a web site in the browser.
If there is no internet connection, the browser calculates forever. It seems as if the call exec ...... is not terminated.
I'm looking forward to your support and hope that someone can tell me what I'm doing wrong.
best regards Hans
It's difficult to predict why it is in your case not working, due to not to be able see your code. But you can try next that works fine. Of Course it's dirty, just is an example.
Next code is for index.js file of the "Node.js Express App + Jade" project that was created from template in WebStorm IDE.
const util = require('util');
const exec = util.promisify(require('child_process').exec);
....
....
router.get('/', async function(req, res, next) {
try {
const {stdout, stderr} = await exec('curl ifconfig.me');
res.render('index', { title: stdout});
}
catch (err) {
res.render('index',{ title: "000.000.000.000"});
}
});
OR use
const util = require('util');
const exec = require('child_process').exec;
function publicIP_www(callback){
exec('curl ifconfig.me',{timeout:3000}, function(error, stdout, stderr){
if (error) {
return callback("000.000.000.000");
}
callback(stdout);
});
}
router.get('/', function(req, res, next) {
publicIP_www((title) => {
res.render('index', { title });
})
});