gpt4 book ai didi

javascript - 使用node.js方法path.extname()时出错

转载 作者:太空宇宙 更新时间:2023-11-03 22:29:58 24 4
gpt4 key购买 nike

我正在使用 Electron 。我编写了一个递归读取目录文件的程序。现在我希望不显示具有特定扩展名(文件扩展名)的文件。为了做到这一点,我需要 node.js 方法 path.extname(path) 来返回扩展名。我的问题是 path.extname() 方法在我需要的代码中的那个位置不起作用。在我的函数 scan_directory_to_html() 之外它可以工作并返回 .jpg 但在函数内部我收到错误 Uncaught TypeError: path.extname is not a function .

const fs = require('fs');
const path = require('path');
const {ipcRenderer} = require('electron')

//This works:
console.log(path.extname(`${__dirname}/../../project_files/sprites/Appenzell.jpg`));

function scan_directory_to_html(directory){
var zw_directory_array = fs.readdirSync(directory);
var zw_to_html = "";

for(var i = 0; i < zw_directory_array.length; i++){
var path = directory + zw_directory_array[i];

//This produces the error message
console.log(path.extname(`${__dirname}/../../project_files/sprites/Appenzell.jpg`));

if(fs.lstatSync(path).isFile()){
zw_to_html += "<a href='#' onClick='create_sprite_window(`"+ path +"`)'><li><img src='" + path + "'/>" + zw_directory_array[i] + "</li></a>";
}else if(fs.lstatSync(path).isDirectory()){

zw_to_html += "<li class='li_directory'>" + zw_directory_array[i] + "</li>";
zw_to_html += "<ul>";
zw_to_html += scan_directory_to_html(path + "/");
zw_to_html += "</ul>";
}else{
console.log("Error in function scan_directory_to_html(): Path is neither directory nor file.");
}
}
return zw_to_html;
}

document.getElementById('sidebar_left_sprites').innerHTML = scan_directory_to_html(`${__dirname}/../../project_files/sprites/`);

我也尝试过输入 const path = require('path');也在函数内部,但它随后表示标识符“路径”已经被声明。如何在函数内部使用 path.extname() 方法?

最佳答案

您的代码中的路径存在冲突。在下面使用另一个名称。

var filepath = directory + zw_directory_array[i];

相反

var path = directory + zw_directory_array[i];

关于javascript - 使用node.js方法path.extname()时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38757815/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com