首页 文章

Node.js - 从服务器读取并下载目录中的所有文件并在本地保存

提问于
浏览
7

我有一个Node Webkit桌面应用程序,需要从服务器下载文件并在用户离线时本地保存 . 当我知道文件名是什么时,我可以下载并保存文件,但是如何读取服务器上目录的内容以便下载每个文件?

function cacheFiles(filelink, filepath, cb) {
    var path_array =  filelink.split("/");
    var foldername =  path_array[path_array.length - 2]

//create new folder for locally html files
var newdir = filepath + '/' + foldername;
if (fs.existsSync(newdir)){
    alert('file already exists, cannot cache this file.');
} else {
    fs.mkdirSync(newdir);
}
//download and save index.html - THIS WORKS
var indexfile = fs.createWriteStream(newdir+'/index.html');
var request = http.get(filelink, function(response) {
    response.pipe(indexfile);
    indexfile.on('finish', function() {
        indexfile.close(cb);
    });
});
//read contents of data folder - THIS DOESN'T WORK
var datafolder = filelink.replace('index.html','');

fs.readdir( datafolder, function (err, datafiles) { 
    if (!err) {
        console.log(datafiles);
    }else{
        console.log(err) ; 
    }   
});

}

我在控制台中遇到的错误是:

“ENOENT:没有这样的文件或目录,scandir'C:\ Users \ my.name \ desktopApp \ app \ http:\ www.mysite.co.uk \ wp-content \ uploads \ wifi_corp2 \ data'”

以上是在本地寻找文件而不是我在 filelink 中提供的在线链接 . http://www.mysite.co.uk/wp-content/uploads/wifi_corp2/data

3 回答

  • 0

    以下代码不读取远程文件系统,它用于读取本地硬盘驱动器上的文件 .

    import fs from 'fs'
    import path from 'path'
    
    fs.readdir(path.resolve(__dirname, '..', 'public'), 'utf8', (err, files) => {
        files.forEach((file) => console.info(file))
    })
    

    将从脚本位置打印出一个目录中的所有文件名,并打印在'public'目录中 . 您可以使用 fs.readFile 来读取每个文件的内容 . 如果它们是JSON,您可以将它们读作utf8字符串并使用 JSON.parse 解析它们 .

    要从远程服务器读取文件,必须通过express或其他静态文件服务器提供这些文件:

    import express from 'express'
    const app = express()
    app.use(express.static('public'))
    app.listen(8000)
    

    然后在客户端,您可以使用fetch或请求http库来调用端口8000上托管的快速 endpoints (在这个简单的示例中) .

  • 1

    您正在将服务器代码与桌面应用程序代码混合在一起 . 显然,桌面应用程序无法在服务器上执行readdir文件 . 只需在Wordpress上安装备份或下载插件即可 .

  • 1

    好吧,我认为最好的方法是使用Ajax调用服务器上的PHP函数来读取文件的内容 .

相关问题