我想使用我的nodeJS的输出。这是我的代码
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 : "";
}
结果是console.log(imageFile)
,我想在我的javascript项目中调用它的结果,比如
<script>
document.write(imageFile)
</script>
所有这些都是为了在目录中创建最新的文件,因为我不能直接在JS上这样做。
非常感谢
发布于 2018-09-27 23:29:39
首先,关于浏览器和web服务器的客户端/服务器关系是如何工作的,我们需要建立一些基本的东西。这将为讨论解决您的问题提供一个框架。
document.write()
在浏览器中显示的,而是通过在文档中插入指向特定图像的URL的图像标记来显示的。有许多可能的方案来实现这种类型的连接。我认为最好的做法是定义一个图像URL,当任何浏览器请求时,它都会返回服务器上特定目录中最新图像的图像。然后,您只需将该特定的URL嵌入到您的web页面中,只要该图像被刷新或显示,您的服务器就会向其发送该图像的最新版本。您的服务器可能还需要通过设置适当的缓存头来确保浏览器不会缓存该URL,这样它就不会错误地只显示该图像以前缓存的版本。
该网页可能如下所示:
<img src='http://mycustomdomain.com/dimages/newest'>
然后,您在mycustomdomain.com
上设置了一个可公开访问的web服务器(从开放的互联网-显然您选择了自己的域),可以访问所需的图像,并在该web服务器上创建一条响应/dimages/newest
请求的路由。
使用Express作为您的web服务器框架,可能如下所示:
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);
发布于 2018-09-27 23:10:19
为了能够在your Javascipt project
中使用产生的,我们必须创建一个具有响应imageFile
的特定路由的API。然后,在您的Javascript项目中,您可以使用XMLHttpRequest (XHR)
对象或Fetch API
与服务器进行交互,以获得结果。
核心思想是我们绝对需要服务器端和客户端编程来执行该功能。
https://stackoverflow.com/questions/52546113
复制相似问题