Pah reference of a static file in node.js - node.js

Hello I cannot access this file, I am getting module not found error, I tried both the root and public folder, can please someone assist with that?
app.use(express.static('public'))
var file = require('public/test.png');

require is specific for nodejs modules, and can't be used for static files
app.use(express.static('public')) Make that public folder is now accessible through your API via yourpath/test.png
What you want is to load image, so you can use it inside a function, therefore, you should use fs
fs.readFile('public/test.png', function(err, data) {
if (err) throw err; // Fail if the file can't be read.
//Do whatever you want with 'data'
});

require is a reserved word, intended to load other nodejs modules but not your website' static assets.
If you follow the steps in the docs, once you do app.use(express.static('public')) your app will automatically serve static files under your "public" folder.
If you need to load a file for some reason, take a look at the fs module.

Related

file preview without downloading it using express

I'm trying to develop a file management web app and I want to add an option to preview files before downloading it I'm using Node Js express, is there any way to implement that.
or just a small guide because I tried all the possible solutions on the net but it's not working
Yes you can preview it, you just need to add declaration for your file path and you can access directly from url
const app = express();
const __dirname = path.resolve()
//public is the name of folder where your file is being stored
app.use("preview",express.static(path.join(__dirname,"public")));
So you can directly access the file using url expressurl/preview/filename and preview it wherever you want
You can use the built in node filesystem module fs to read and write to files on the server. So in your case you want to read the content of files, so something like this:
var fs = require('fs');
fs.readFile('my-file.txt', 'utf8', function(err, data) {
if (err) throw err;
console.log(data);
});

Can someone please explain how static files in express js work?

I am new with nodejs and much more new with express module. I have a app setup like this;
The chart.js is my nodejs file. I am trying to make my js files and css file static by using app.use(express.static(-I didn't understand what i need to write here-)) in order to render my index.html properly but I don't know how to use and I did not understand the documentation. In the documentation they say coder able to use static like app.use(express.static('public')) but they don't mention about what is public, where it is in the project, what does it contain. Can someone please help mi about this situation? How does this express.static works and how can I make my files static?
NOTE: DO NOT PUT PRIVATE FILES INSIDE YOUR STATIC FOLDER.
app.use(express.static(__dirname + '/public'));
here you see inside of express.static() function is the path of your static folder that will be going to access directly from the browser and you don't need to write their routes because that folder will give all the access to the public. like css,js files. and those files you will be able to access as its directory.
in the above picture, you have html, css and js files in public folder which is located on root folder of the application. you need to access those public static files which are not related to nodejs so it should be defined as static on your server node js code as : app.use(express.static(__dirname + '/public'));. and it will get all the routes like:
http://localhost:3000/css/style.css
http://localhost:3000/javascript/script.js
http://localhost:3000/favicon.ico
http://localhost:3000/index.html
http://localhost:3000/robots.txt
you also can set prefix for those static routes. for that, you need to give prefix as: app.use('static_folder', express.static(__dirname + '/public')); then it will be looks like :
http://localhost:3000/static_folder/css/style.css
http://localhost:3000/static_folder/javascript/script.js
http://localhost:3000/static_folder/favicon.ico
http://localhost:3000/static_folder/index.html
http://localhost:3000/static_folder/robots.txt

How to dynamically create/modify sitemap.xml file in angular 9 project structure at runtime?

How to create dynamic sitemap.xml file in Angular 9 project structure ? I can get data using HTTP get request from node API but using this data how can I update local xml file from angular project at runtime ?
In my case, angular project and node project are on different server(different domain). And It is possible to create xml file in node project but I am not able to access that file as xml file in angular project root .
Can anyone please suggest me how to use node xml in angular project OR is it possible to create/modify dynamic sitemap.xml using api call in Angular 9?
Any help would be greatly appreciated.
I am working on the same subject now and I have achieved something.
I added it in the angular.json file like this
Then I created a component and specified its path as sitemap.xml.
It is possible to perform server-side rendering in Angular, and with that, our job is a little easier. Angular Server Side Rendering
You can add a new routing to your routing.module file and interfere with this request via server.ts
For example, you can access a route like sitemap.xml in this way in server.ts.
server.get('/sitemap.xml', (req, res, next) => { bla,bla }
You can now access the file you want here and change it as you wish.
File operations in server.ts
function writeFile(sitemap: string): void {
const fs = require('fs');
fs.appendFile('../sitemap.xml', sitemap, (err) => {
if (err) {
throw err;
}
console.log('Saved!');
});
}
then, redirect operations
res.redirect('http://localhost:{$PORT}/sitemap.xml');

cannot reach a file on server though I exposed using express

In my project I need to store some text files dynamically and end user should be able to download them from browser. I know the best way is using object store like MINIO or S3 but unfortunately the only way I have is to use in memory storage. So what I am trying to do is: I made a public folder and I exposed it using the following code:
var express = require('express');
var app = express();
//setting middleware
app.use(express.static( 'public')); //Serves resources from public folder
var server = app.listen(5000);
it is as simple as that. Then for testing just to make sure I can download and reach a file I created a public folder with t.txt file in it and when I try:
http://localhost:5000/public/t.txt
I get
So why am I not getting it? Also is what I am trying to achieve will be a good match to scenario and is it doable at all?
When you're not specifying a path in app.use(), your app will serve the contents of the directory you're pointing to in express.static() on the root path. Try this:
http://localhost:5000/t.txt
That said, if you want it to be accessible at /public/t.txt, just specify the path:
app.use('/public', express.static('public'))
At first use the following line of code:
app.use(express.static(__dirname+'/public'));
This means that your home directory for static HTML pages is in the "public" folder. Note that the "__dirname" points to the directory of the current js file.
After that, call the following URL from the browser or POSTMAN:
http://localhost:5000/t.txt
As you can see, there is no need to write http://localhost:5000/public/t.txt referring to the "public" folder because you have already specified that in the app.use line.

Read files from folder before start

I want to get an array of file names from my project public/logos folder. I am using create-react-app template and as you guess, I can not use const fs = require('fs') in browser after project start.
So, is there any way to fill an array right after npm start command and getting file names array from folder or am I out of context?
const fs = require('fs')
const path = require('path')
const appRoot = require('app-root-path').path
const getNames = () => {
fs.readdir(path.join(appRoot, "public", "logos"), (err, files) => {
return files
})
}
Although the Sathishkumar is correct, it's not the only way: having an application server just for reading static images can be too much in many situations.
What you can do is to handle this by change the webpack configuration (this requires you eject first so be really careful).
From webpack you have all of the Nodejs features available but you must make those changes static for the webapp.
An idea:
manually copy with html-copy-plugin every image in the dist folder
read every image file in that folder from node and generate a list of image names
put the list of images as a global variable in your bundle by using webpack DefinePlugin
Now you will be able to read images names from this new global.
Note: this will not be a dynamic read of resources in a folder. If add/remove images you will be forced to repeat the build process of the app.
Yes. It is out of context. Not possible in browser-based JS application. You can't access the file system using Javascript in the browser.
You can use a NodeJS(or any other language for the same) to create a REST API as you mentioned which will return the files list and then can consume it(APIs like fetch or package - axios) in the frontend. This is the preferred way of doing.
If you need to read the files from file system you need to start server, like express, and then read this files on the server by request from frontend or by the link you pasted in your browser address field.

Resources