how to use a nodeJS out in javascript file

I would like to use the output of my nodeJS. This is my code

var fs = require('fs'); //File System
var rutaImagen = 'C:/Users/smontesc/Desktop/imagenes1/'; //Location of images
fs.readdir(rutaImagen, function(err, files) {
    if (err) { throw err; }
    var imageFile = getNewestFile(files, rutaImagen);
    //process imageFile here or pass it to a function...
    console.log(imageFile);
});

function getNewestFile(files, path) {
    var out = [];
    files.forEach(function(file) {
        var stats = fs.statSync(path + "/" +file);
        if(stats.isFile()) {
            out.push({"file":file, "mtime": stats.mtime.getTime()});
        }
    });
    out.sort(function(a,b) {
        return b.mtime - a.mtime;
    })
    return (out.length>0) ? out[0].file : "";
}

And the result is console.log(imageFile), I want to call the result of this in my javascript project, like

<script>
  document.write(imageFile)
</script>

All this is to get the newest file created in a directory because I can't do it directly on JS.

Thanks a lot

Upvotes: 0

Views: 60

Answers (2)

jfriend00
jfriend00

Reputation: 707258

First, there are several fundamental things about how the client/server relationship of the browser and a web server work that we need to establish. That will then offer a framework for discussing solving your problem.

  1. Images are displayed in a browser, not with document.write(), but by inserting an image tag in your document that points to the URL of a specific image.

  2. For a web page to get some result from the server, it has to either have that result embedded in the web page when the web page was originally fetched from the server or the Javascript in the web page has to request information from the server with an Ajax request. An ajax request is an http request where the Javascript in your web page, forms an http request that is sent to your server, your server receives that request and sends back a response which the Javascript in your web page receives and can then do something with.

  3. To implement something where your web page requests some data from your back-end, you will have to have a web server in your back-end that can response to Ajax requests sent from the web page. You cannot just run a script on your server and magically modify a web page displayed in a browser. Without the type of structure described in the previous points, your web page has no connection at all to the displayed server. The web page can't directly reach your server file system and the server can't directly touch the displayed web page.

There are a number of possible schemes for implementing this type of connection. What I would think would work best would be to define an image URL that, when requested by any browser, it returns an image for the newest image in your particular directory on your server. Then, you would just embed that particular URL in your web page and anytime that image was refreshed or displayed, your server would send it the newest version of that image. Your server probably also needs to make sure that the browser does not cache that URL by setting appropriate cache headers so that it won't mistakenly just display the previously cached version of that image.

The web page could look like this:

<img src='http://mycustomdomain.com/dimages/newest'>

Then, you'd set up a web server at mycustomdomain.com that is publicly accessible (from the open internet - you choose your own domain obviously) that has access to the desired images and you'd create a route on that web server that answers to the /dimages/newest request.

Using Express as your web server framework, this could look like this:

const app = require('express')();
const fs = require('fs');
const util = require('util');
const readdir = util.promisify(fs.readdir);
const stat = util.promisify(fs.stat);

// middleware to use in some routes that you don't want any caching on
function nocache(req, res, next) {
    res.header('Cache-Control', 'private, no-cache, no-store, must-revalidate, proxy-revalidate');
    res.header('Expires', '-1');
    res.header('Pragma', 'no-cache');
    next();
}

const rutaImagen = 'C:/Users/smontesc/Desktop/imagenes1/'; //Location of images

// function to find newest image
// returns promise that resolves with the full path of the image
//    or rejects with an error
async function getNewestImage(root) {
    let files = await readdir(root);
    let results = [];
    for (f of files) {
        const fullPath = root + "/" + f;
        const stats = await stat(fullPath);
        if (stats.isFile()) {
            results.push({file: fullPath, mtime: stats.mtime.getTime()});
        }
    }
    results.sort(function(a,b) {
        return b.mtime - a.mtime;
    });
    return (results.length > 0) ? results[0].file : "";            
}

// route for fetching that image
app.get(nocache, '/dimages/newest', function(req, res) {
    getNewestImage(rutaImagen).then(img => {
        res.sendFile(img, {cacheControl: false});
    }).catch(err => {
        console.log('getNewestImage() error', err);
        res.sendStatus(500);
    });
});

// start your web server
app.listen(80);

Upvotes: 2

Tu Nguyen
Tu Nguyen

Reputation: 10179

To be able to use that result in your Javascipt project, we definitely have to create an API which has a particular route that responses the imageFile. Then, in your Javascript project, you can use XMLHttpRequest (XHR) objects or the Fetch API to interact with servers to get the result.

The core idea is we definitely need both server-side and client-side programming to perform that functionality.

Upvotes: 0

Related Questions