How to download file from deployed server? - javascript

Can someone tell me why function below properly download my file from server when i work locally (by localhost) but not download me and return me 500 internal server error when i try do is when i deploy my app on remote server?
async downloadFile(fileId: number): Promise<Buffer> {
const fileName = await this.getFileName(fileId);
const fileBuffer = await new Promise<Buffer>((resolve, reject) => {
fs.readFile(process.cwd() + '/files/' + fileName + '.xlsx', {}, (err, data) => {
if (err) reject(err)
else resolve(data)
});
});
return fileBuffer ;
}
thanks for any help
EDIT, ERROR FROM LOG:
ENOENT: no such file or directory

If you are willing to access your file relatively to your script dir you should use __dirname
Also using the path module in order to build your file location in a platform agnostic way is a good practice.
const path = require('path')
const filePath = path.join(__dirname, 'files', `${fileName}.xlsx`)
process.cwd() refers to you node process working dir. Using it in your context would tie your code to how the entry point has been called. This is bad. Code should not have to be aware of its execution context to work whenever this is possible.
An even better way would be to make your file location configurable (using an environment variable or a config file) and pass your download folder value to your code this way.
see https://12factor.net/config
example
const baseDir = process.env.FILES_PATH || '/some/default/location';
const filePath = path.join(baseDir, 'files', `${fileName}.xlsx`);
then run your program with
FILES_PATH=/your/directory node your_script.js

Related

How to use code which runs in browser and outside browser together (node.js filesystem)

I want to enter path to the folder in browser and display all file names which located inside, i found that it will possible with node fs, but i also have code which runs at browser, and it need vars, located in file, which will run outside of the browser with node. I need to create server with node and runs all code from it? Or what you can reccomend me to reach this goal? PS: By the way i use webpack
There are differences between javascript in browser end and server end. You can't access the directory directly from the browser. You need some sort of backend technology like PHP, Java, node, python, etc in order to get the file list. You can use node server and below code for the reading directory. Then make a simple HTTP request to your backend server from the frontend.
const path = require('path');
const express = require('express');
const fs = require('fs');
const PORT = 3000;
const app = express();
app.get('/getfiles', async (req, res) => {
const directoryPath = path.join(__dirname, 'Documents');
let data = [];
await fs.readdir(directoryPath, function (err, files) {
//handling error
if (err) {
return console.log('Unable to scan directory: ' + err);
}
//listing all files using forEach
files.forEach(function (file) {
// Do whatever you want to do with the file
data.push(file)
});
});
res.send(data);
});
app.listen(PORT, ()=>{
console.log(`server running on port ${PORT}`);
});

Electron doesn't add json file to application

This is my first electron/node application, I m trying to use a json file as a datastore. so I created a simple one index.json under the app folder next to index.js|css|html
I installed a npm package jsonfile that is loading just fine
When I try to load my json file the EOF is rised claiming that there is no json file, and I can see that using the DevTools source tab that my json file is not there ( not loaded )
I tried force reload from electron app menu.
Here is my files code that is reading my json
const jsonfile = require('jsonfile')
const file = '/index.json';
var json;
jsonfile.readFile(file)
.then(obj => json = obj)
.catch(error => console.error(error))
------------ Edit
correcting the path name to index.json or ./index.json rises the same issue
You can use the native fs (filesystem) module.
let path = "index.json"
const fs = require('fs');
const json = JSON.parse(fs.readFileSync(path));
Thanks for your support
For me the issue was more about file system handling than electron.
All I did is to chmod my project folder to assure that I will be able to read and write into the index.json datastore
sudo chmod -R 777 /opt/workspaces/electron/myElectronPrpjectFolder
Then for a better path resolution I used the basic idea used in electron archtype, It more error safe
const path = require('path')
const file = path.join(__dirname,'index.json');
var json;
var html = "";// The returned object.
$(document).ready(function () {
jsonfile.readFile(file)
.then(obj => {
json = JSON.parse(JSON.stringify(obj));
console.log(JSON.stringify(json))
parseIssues(json.children);
document.getElementById('a').innerHTML = html;
})
.catch(error => console.error(error))
});
You can see that I m using JQuery in this snippet but it also works without JQuery.
in resume, better path resolve policy with granted priveleges on folder.
Thanks

Node only sends html content to the client instead of sending a whole Vue app

I created a new vue project with the CLI and want to deploy it. Based on this documentation
https://router.vuejs.org/guide/essentials/history-mode.html#html5-history-mode
I added the history mode to the router. After running npm run build I took the example code for a static native Node server
https://router.vuejs.org/guide/essentials/history-mode.html#example-server-configurations
const http = require('http')
const fs = require('fs')
const httpPort = 3000
http.createServer((req, res) => {
fs.readFile('../base/index.html', 'utf-8', (err, content) => {
if (err) {
throw err;
}
res.writeHead(200, {
'Content-Type': 'text/html; charset=utf-8'
})
res.end(content)
})
}).listen(httpPort, () => {
console.log('Server listening on: http://localhost:%s', httpPort)
})
So when navigating to localhost:3000 the vue project seems to load correctly
but I have a blank page with two errors
When I click on those js files it shows me the content of the index.html file. Obviously js is not able to understand this html content. How can I fix that problem?
Server will not send the whole vue app at once.
Browser get html file from server, when you browse to that url.
Browser parse the html file.
Browser detects assets (js, images, css).
Browser request those files.
It request those file from server, but you haven't initialized server to find those files.
So, need to add static files.
https://expressjs.com/en/starter/static-files.html
You can take reference from here
as #Sukul answer before, you just need to server the static files because you have now only one handler to server all the request coming with the HTML file (the mount point document) and when its requesting the *.js app it's expecting the valid javascript syntax instead it finds HTML, and that what the error messages are on the network tab
const http = require('http')
const fs = require('fs')
const nStatic = require('node-static');
var fileServer = new nStatic.Server('./public');
const httpPort = 3000
const controllers = (req,res)=>{
if(req.url.includes(".")
return fileServer.serve(req, res);
else
fs.readFile('../base/index.html', 'utf-8', (err, content) => {
if (err) {
throw err;
}
res.writeHead(200, {
'Content-Type': 'text/html; charset=utf-8'
})
res.end(content)
})
}
}
http.createServer(controllers).listen(httpPort, () => {
console.log('Server listening on: http://localhost:%s', httpPort)
})
node-static ref
however, I highly recommend you trying to use express.js

How to get files contained in a path

In the following path:
app/test/vehicle/
there are several .js file. Is there any way in Javascript where I can get the number of .js file contains in the above-mentioned path?
I am using webStorm environment
Yes, using node:
const fs = require('fs');
const dir = './directory';
fs.readdir(dir, (err, files) => {
console.log(files.length);
});
https://stackoverflow.com/a/43747896/3650835
Since javascript doesn't have local filesystem access when run in the browser, there is no way to access local files from javascript. If you are asking about accessing all files hosted on a cdn or something similar in that directory, there is still no way to tell which requests will return a 20x.
If you are using nodejs, use the fs.readdir function:
const fs = require('fs');
fs.readdir('app/test/vehicle/', (err, files) => {
files.forEach(file => { console.log(file);} );
})
There is no way to access the file system from a web page.
If you are using nodejs, then you can use fs.readdir or fs.readdirSync:
const fs = require('fs');
const dir = './directory';
fs.readdir(dir, (err, files) => {
console.log(files.filter(file => file.endsWith(".js")).length);
});
Where are you trying to get list of the files? On the client side it is impossible. JavaScript does not have access to the client file system. If you are trying to do it in the server side using for example node.js then you can do something like:
var filesys = require('fs');
var files = filesys.readdirSync('/app/test/vehicle/');

How do I use javascript to get a list of files from my server's '/public/Docs' in my Node.js solution?

On Windows 7. In a proprietary app that contains chromium browser. Running on Node.js and Express. In my file 'javascripts/getMyFiles.js' I'm trying to use the following code from: http://nodeexamples.com/2012/09/28/getting-a-directory-listing-using-the-fs-module-in-node-js/
#!/usr/bin/env node
var fs = require("fs"),
path = require("path");
var p = "../"
fs.readdir(p, function (err, files) {
if (err) {
throw err;
}
files.map(function (file) {
return path.join(p, file);
}).filter(function (file) {
return fs.statSync(file).isFile();
}).forEach(function (file) {
console.log("%s (%s)", file, path.extname(file));
});
});
I have 3 problems with this code:
I get and 'Unexpected token ILLEGAL' error from the '#!/use/bin/end node' line
After deleting that first line of code I get the error 'Uncaught ReferenceError: require is not defined'. If I move the '...require...' lines to my root app.js file then the object fs is undefined in my getMyFiles.js file.
I need to specify which folder to list when my app gets an event
I get that require is not available on the client-side, but I don't want to get a list of files from the client side. The files I want to list are in the same path as all of my other files, '/public/Docs'. I can load a known file straight away, but I need to present the user with a list of available documents first. Any assistance will be most appreciated.

Categories