如何使用node.js获取当前目录名并显示在html页面上
Posted
技术标签:
【中文标题】如何使用node.js获取当前目录名并显示在html页面上【英文标题】:How to get the current directory name and display it on the html page using node.js 【发布时间】:2016-02-04 22:43:42 【问题描述】:实际上我在 index.js 文件中有一个路径名。每当我选择目录时,我都能在 node.js 控制台屏幕中看到当前目录名。
现在,我想将该目录名称显示到template.html
页面的文本框中。谁能帮我解决这个问题?
在 index.js 中,这部分我可以在控制台中看到路径名:
app.get('/files', function(req, res)
var currentDir = dir;
var query = req.query.path || '';
if (query) currentDir = path.join(dir, query);
console.log("browsing ", currentDir);
我的 index.js:
#!/usr/bin/env node
var http = require('http');
var _ = require('lodash');
var express = require('express');
var fs = require('fs');
var path = require('path');
var util = require('util');
var program = require('commander');
function collect(val, memo)
if(val && val.indexOf('.') != 0) val = "." + val;
memo.push(val);
return memo;
program
.option('-p, --port <port>', 'Port to run the file-browser. Default value is 8088')
.option('-e, --exclude <exclude>', 'File extensions to exclude. To exclude multiple extension pass -e multiple times. e.g. ( -e .js -e .cs -e .swp) ', collect, [])
.parse(process.argv);
var app = express();
var dir = process.cwd();
app.use(express.static(dir)); //app public directory
app.use(express.static(__dirname)); //module directory
var server = http.createServer(app);
if(!program.port) program.port = 8088;
server.listen(program.port);
console.log("Please open the link in your browser http://<YOUR-IP>:" + program.port);
app.get('/files', function(req, res)
var currentDir = dir;
var query = req.query.path || '';
if (query) currentDir = path.join(dir, query);
console.log("browsing ", currentDir);
fs.readdir(currentDir, function (err, files)
if (err)
throw err;
var data = [];
files
.filter(function (file)
return true;
).forEach(function (file)
try
//console.log("processing ", file);
var isDirectory = fs.statSync(path.join(currentDir,file)).isDirectory();
if (isDirectory)
data.push( Name : file, IsDirectory: true, Path : path.join(query, file) );
else
var ext = path.extname(file);
if(program.exclude && _.contains(program.exclude, ext))
console.log("excluding file ", file);
return;
data.push( Name : file, Ext : ext, IsDirectory: false, Path : path.join(query, file) );
catch(e)
console.log(e);
);
data = _.sortBy(data, function(f) return f.Name );
res.json(data);
);
);
app.get('/', function(req, res)
res.redirect('lib/template.html');
);
我的模板.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>File Browser</title>
<link rel="stylesheet" href="/lib/bootstrap.min.css">
<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css">
<link rel="stylesheet" href="/lib/app.css">
</head>
<body>
<div id="panelDiv">
<div class="panel-heading">
<button type="button" id="butDiv" >Browse</button>
<input type="text" name="location"/>
<span class="up">
<i class="fa fa-level-up"></i> Up
</span>
</div>
<div id="showDiv" class="panel-body">
<table class="linksholder">
</table>
</div>
</div>
<script src="/lib/jquery.min.js"></script>
<script src="/lib/bootstrap.min.js"></script>
<script src="/lib/datatable/js/jquery.datatables.min.js"></script>
<script src="/lib/app.js"></script>
<script>
$(document).ready(function()
$("#butDiv").click(function()
$("#showDiv").toggle();
);
);
</script>
</body>
</html>
我的 app.js:
(function($)
var extensionsMap =
".zip" : "fa-file-archive-o",
".gz" : "fa-file-archive-o",
".bz2" : "fa-file-archive-o",
".xz" : "fa-file-archive-o",
".rar" : "fa-file-archive-o",
".tar" : "fa-file-archive-o",
".tgz" : "fa-file-archive-o",
".tbz2" : "fa-file-archive-o",
".z" : "fa-file-archive-o",
".7z" : "fa-file-archive-o",
".mp3" : "fa-file-audio-o",
".cs" : "fa-file-code-o",
".c++" : "fa-file-code-o",
".cpp" : "fa-file-code-o",
".js" : "fa-file-code-o",
".xls" : "fa-file-excel-o",
".xlsx" : "fa-file-excel-o",
".png" : "fa-file-image-o",
".jpg" : "fa-file-image-o",
".jpeg" : "fa-file-image-o",
".gif" : "fa-file-image-o",
".mpeg" : "fa-file-movie-o",
".pdf" : "fa-file-pdf-o",
".ppt" : "fa-file-powerpoint-o",
".pptx" : "fa-file-powerpoint-o",
".txt" : "fa-file-text-o",
".log" : "fa-file-text-o",
".doc" : "fa-file-word-o",
".docx" : "fa-file-word-o",
;
function getFileIcon(ext)
return ( ext && extensionsMap[ext.toLowerCase()]) || 'fa-file-o';
var currentPath = null;
var options =
"bProcessing": true,
"bServerSide": false,
"bPaginate": false,
"bAutoWidth": false,
"sScrollY":"250px",
"fnCreatedRow" : function( nRow, aData, iDataIndex )
if (!aData.IsDirectory) return;
var path = aData.Path;
$(nRow).bind("click", function(e)
$.get('/files?path='+ path).then(function(data)
table.fnClearTable();
table.fnAddData(data);
currentPath = path;
);
e.preventDefault();
);
,
"aoColumns": [
"sTitle": "", "mData": null, "bSortable": false, "sClass": "head0", "sWidth": "55px",
"render": function (data, type, row, meta)
if (data.IsDirectory)
return "<a href='#' target='_blank'><i class='fa fa-folder'></i> " + data.Name +"</a>";
else
return "<a href='/" + data.Path + "' target='_blank'><i class='fa " + getFileIcon(data.Ext) + "'></i> " + data.Name +"</a>";
]
;
var table = $(".linksholder").dataTable(options);
console.log(table);
$.get('/files').then(function(data)
table.fnClearTable();
table.fnAddData(data);
);
$(".up").bind("click", function(e)
if (!currentPath) return;
var idx = currentPath.lastIndexOf("/");
var path =currentPath.substr(0, idx);
$.get('/files?path='+ path).then(function(data)
table.fnClearTable();
table.fnAddData(data);
currentPath = path;
);
);
)(jQuery);
当前浏览格式:
必需的浏览格式:
【问题讨论】:
【参考方案1】:假设您的 template.html
只是一个静态 html 页面而不是模板,那么只有一种方法可以从服务器获取数据 - 通过 xhr 请求。您可以在index.js
中再添加一条路线:
//...
app.get('/', function(req, res)
res.redirect('lib/template.html');
);
app.get('/directory', function(req, res)
var currentDir = dir;
var query = req.query.path || '';
if (query) currentDir = path.join(dir, query);
var data = directory: currentDir
res.json(data);
);
然后从您的app.js
触发另一个 xhr 请求(到此路由):
$.get('/directory').then(function(data)
$("input[name='location']").val(data.directory);
);
另外,将其添加到.up
事件处理程序:
$(".up").bind("click", function(e)
if (!currentPath) return;
var idx = currentPath.lastIndexOf("/");
var path =currentPath.substr(0, idx);
$.get('/files?path='+ path).then(function(data)
table.fnClearTable();
table.fnAddData(data);
currentPath = path;
);
$.get('/directory?path='+ path').then(function(data)
$("input[name='location']").val(data.directory);
);
);
并修改fnCreatedRow
:
"fnCreatedRow" : function( nRow, aData, iDataIndex )
if (!aData.IsDirectory) return;
var path = aData.Path;
$(nRow).bind("click", function(e)
$.get('/files?path='+ path).then(function(data)
table.fnClearTable();
table.fnAddData(data);
currentPath = path;
);
$.get('/directory?path='+ path').then(function(data)
$("input[name='location']").val(data.directory);
);
e.preventDefault();
);
,
您也可以将此数据添加到/files
路由响应。
另一种方法是使用模板。 Here 您可以在 express 中阅读有关模板引擎的信息。
【讨论】:
非常感谢您的帮助。实际上我在文本框中得到了斜线。但我想在该文本框中显示当前目录路径。请帮助我解决这个问题... 这里我可以得到斜杠的值。但是不能得到当前目录的路径。 $.get('/directory').then(function(data) $("input[name='location']").val(data.directory); ); 你能帮帮我吗?我无法在响应中获取目录路径。在 json 中,我也只得到斜线作为输出。我没有得到我的位置我出错了 我现在很忙,一两个小时后会回来帮您。 其实,我可以将当前路径放入文本框。以上是关于如何使用node.js获取当前目录名并显示在html页面上的主要内容,如果未能解决你的问题,请参考以下文章
如何使用 node.js 和 Promises 将特定行的行添加到文件的内容
如何使用本机反应像 Node.js 一样获取`__dirname`
如何从给定 ID 获取用户信息并使用 Node.js 和 EJS 显示它[关闭]
如何以 Node JS 作为后端将 Mysql 数据获取并显示到 ReactJS 前端?