Error when using node.js method path.extname() - javascript

I am using Electron. I have written a program that recursively reads the files of a directory. Now I want that files with a certain extname (file extension) are not shown. In order to do that I need the node.js method path.extname(path) which return the extname.
My problem is that the path.extname() method does not work at that place in the code I need it.
Outside of my function scan_directory_to_html() it works and returns .jpg but inside of the function I get the error 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/`);
I have also tried to put const path = require('path'); inside the function as well but it then says that the Identifier 'path' has already been declared.
How can I use the path.extname() method inside of the function?

The path is conflicted in your code. Use another name in below.
var filepath = directory + zw_directory_array[i];
instead
var path = directory + zw_directory_array[i];

Related

Unable to fetch all text file names recursively from a directory

I'm trying to fetch all text files from a directory in a recursive manner (i.e. search all sub-folders):
let fs = require("fs");
function getPathNames(dirName) {
let pathNames = [];
for (let fileName of fs.readdirSync(dirName)) {
let pathName = dirName + "/" + fileName;
if (fs.statSync(pathName).isDirectory())
pathNames.concat(getPathNames(pathName));
else if (pathName.endsWith(".txt"))
pathNames.push(pathName);
}
return pathNames;
}
However, when I call getPathNames("."), I get only the name of the first file.
It works fine if I take the return-value out of the function, and update a global variable instead:
let fs = require("fs");
let pathNames = [];
function getPathNames(dirName) {
for (let fileName of fs.readdirSync(dirName)) {
let pathName = dirName + "/" + fileName;
if (fs.statSync(pathName).isDirectory())
getPathNames(pathName);
else if (pathName.endsWith(".txt"))
pathNames.push(pathName);
}
}
Does anyone spot anything wrong with the first method?
Well, concat is not an in place mutation, but returns you a new array instead, so I would say you should do this instead
pathNames = pathNames.concat(getPathNames(pathName));

How to get the executed javascript file directory?

I have a javascript file in a directory like:
/httpdocs/wp-content/themes/themeName/users/js
And there are some PHP files I want to make Ajax Requests to in this directory:
/httpdocs/wp-content/themes/themeName/users
How to get the PHP files directory in Javascript/Jquery?
If you have a file referenced (say, in <head>) on your page
<head>
<script src="~/httpdocs/wp-content/themes/themeName/users/js/test-file.js"></script>
</head>
you can pass the file name (without the .js extension) into this function, together with it's folder name, and it should return the path with the folder name removed:
$(function () {
var getFilePath = function (fileName, scriptFolderName) {
var reg = new RegExp("" + fileName + ".*\\.js");
var regReplace = new RegExp("/" + scriptFolderName + "/" + fileName + ".*\\.js.*$");
// Find the file in the page
var fileSrc = $("script[src]").filter(function () {
return reg.test($(this).attr("src"));
}).first();
if (0 === fileSrc.length) {
console.log("Could not get location of " + fileName + ".js");
} else {
// Return the path without parent folder
return fileSrc.attr("src").replace(regReplace, "/");
}
};
// Call the function with the referenced filename and folder
// (the function could be adjusted to remove the need for the
// folder name, by hardcoding it, but this is more flexible)
var filePath = getFilePath("test-file", "js");
console.log("filePath: : " + filePath);
});

uwp javascript list files in music library folder

The following lists files in a folder "Assets" in app and functions correctly.
// Get the path to the app's Assets folder.
var root = Windows.ApplicationModel.Package.current.installedLocation.path;
var path = root + "\\Assets";
//var path = Windows.Storage.KnownFolders.musicLibrary;
var StorageFolder = Windows.Storage.StorageFolder;
var folderPromise = StorageFolder.getFolderFromPathAsync(path);
folderPromise.done(function getFolderSuccess(folder) {
var filesInFolderPromise = folder.getFilesAsync();
filesInFolderPromise.done(function getFilesSuccess(filesInFolder) {
s = "";
filesInFolder.forEach(function forEachFile(item) {
s = s + item.name + "<br />";
});
document.getElementById('filelist').innerHTML = s;
});
});
I want to modify it to list the files in the musicLibrary. When I change the path name to
var path = Windows.Storage.KnownFolders.musicLibrary;
I get
JavaScript runtime error: The parameter is incorrect
Please help me with the appropriate syntax. The musicLibrary capability is set in the manifest.
Windows.Storage.KnownFolders.musicLibrary
is not a path string. This is StorageFolder class. Thus the call of getFolderFromPathAsync fails. Please refer the Microsoft docs.
KnownFolders Class (You can select 'JavaScript' from the language combobox on the right pane)
The object is to get the files async from the Music folder. This is done directly as follows:
var f = Windows.Storage.KnownFolders.musicLibrary;
f.getFilesAsync().done(function getFilesSuccess(filelist) {
s = "";
filelist.forEach(function forEachFile(item) {
s = s + item.name + "<br />";
});
document.getElementById('filelist').innerHTML = s;
});
Thanks to pnp0a03, and a quick re reading of the documentation.
For those struggling with syntax, this answer is equivalent:
var f = Windows.Storage.KnownFolders.musicLibrary;
f.getFilesAsync().then(success42);
function success42(filelist) {
s = "";
filelist.forEach(function forEachFile(item) {
s = s + item.name + "<br />";
});
document.getElementById('filelist').innerHTML = s;
}

How do I get $.getJSON to work on JSONP

I know it looks like a lot but my question pertains to a single line of (bolded) code. I know my event handler is set up correctly. I know my url is what it should be by this point, except for the ?callback=? part (I read in another post that by putting this at the end of the url passed to $.getJSON, the getJSON becomes capable of working with JSONP, and according to their API page wiki uses JSONP). I also know for certain that the domMod function NEVER RUNS, NOT EVEN THE FIRST LINE OF IT. So don't worry about the other parts of my code, just please if you can tell me why my $.getJSON is not calling the function, I am really new to this stuff. The error message I get back is
wikiViewer.html:1 Refused to execute script from
'https://en.wikipedia.org/w/api.php?format=json&action=query&generator=searc…=jordan?callback=jQuery111107644474213011563_1454965359373&_=1454965359374'
because its MIME type ('application/json') is not executable, and
strict MIME type checking is enabled.
(function(){
var searchBtn = document.getElementById('search');
//var body = document.getElementsByTagName('body')[0];
var input = document.getElementById("input");
var bodyDiv = document.getElementById('bodyDiv')
$(document).ready(function(){
searchBtn.addEventListener('click', searchWiki);
function searchWiki(){
bodyDiv.innerHTML = "";
var url = 'https:\/\/en.wikipedia.org/w/api.php?format=json&action=query&generator=search&gsrnamespace=0&gsrlimit=10&prop=pageimages|extracts&pilimit=max&exintro&explaintext&exsentences=1&exlimit=max&gsrsearch='
if (input.value === ""){
return;
}
var searchTerm = input.value.replace(/\s/g, '%20');
url = url + searchTerm + "?callback=?";
**$.getJSON(url, domMod)** //change fileName to be whatever we wish to search
function domMod(json){ //what to do with dom based on json file NOTE WE NEED TO FIRST CHECK ANDREMOVE PREVIOUS SEARCH CONTENT
var entry;
if (!json.hasOwnProperty(query)){
return;
}
if (!json.query.hasOwnProperty(pages)){
return;
}
json = json.query.pages;
var keys = Object.keys(json);
var keysLength = keys.length;
for (var i = 0; i < keysLength; i++){
entry = json[keys[i]];
var outterDiv = document.createElement('div');
outterDiv.className = "entry";
var imageDiv = document.createElement('div');
imageDiv.className = "entryImg";
var entryDiv = document.createElement('div');
entryDiv.className = "entryTxt";
outterDiv.appendChild(imageDiv);
outterDiv.appendChild(entryDiv);
entryDiv.innerHTML = '<h2>' + entry.title + '</h2>' + '<p>' + entry.extract + '</p>'
if (entry.hasOwnProperty('thumbnail')){ //add image to our imageDiv child of entryDiv
imageDiv.style.backgroundImage = "url('" + entry.thumbnail.source + "')"
}
bodyDiv.appendChild(outterDiv); //appendChild to the Body
}
}
}
});
}())
You already have a query string started in url using ? but are adding another ? when you do:
url = url + searchTerm + "?callback=?";
Change to
url = url + searchTerm + "&callback=?";
Works fine when I sent term "food"
DEMO

My custom javascript function is "not a function"?

I wrote a small .js file that has 3 functions in it for easy in-site cookie management. Here is the source for that file:
// Make Cookie
function Bake(name,value) {
var oDate = new Date();
oDate.setYear(oDate.getFullYear()+1);
var oCookie = encodeURIComponent(name) + '=' + encodeURIComponent(value) + ';expires=' + oDate.toGMTString() + ';path=/';
document.cookie= oCookie;
}
// Read Cookie
function Eat(name){
name = name.toLowerCase();
var oCrumbles = document.cookie.split(';');
for(var i=0; i<oCrumbles.length;i++)
{
var oPair= oCrumbles[i].split('=');
var oKey = decodeURIComponent(oPair[0].trim().toLowerCase());
var oValue = oPair.length>1?oPair[1]:'';
if(oKey == name)
return decodeURIComponent(oValue);
}
return '';
}
// Delete / Void Cookie
function Burn(name){
Bake(name,'');
}
I put that .js file into my "/models" folder on Cloud9. In my index.js I do have the line: var OCookie = require('../models/oatmealcookie'); to include my custom "library". However, still in index.js, I attempt to call the OCookie.Bake('test','testvalue'); before a redirect, and an error comes up on the page as TypeError: OCookie.Bake is not a function. Any help as to why it's not able to recognise my function as a function?
If that is your whole file, you aren't exporting any of your functions through module.exports. Effectively, your file is run once, and Bake, Eat, and Burn are declared as functions for the module but no other module can use them.
You would need something like:
module.exports = {
Bake: Bake,
Eat: Eat,
Burn: Burn
};
So that other modules can use your functions.
You need an exports.Bake = Bake at the end of the module.
You need to export your functions so that node.js recognises them when you require them.
See here: http://www.sitepoint.com/understanding-module-exports-exports-node-js/ for example.
var exports = module.exports = {
// Make Cookie
'Bake': function (name,value) {
var oDate = new Date();
oDate.setYear(oDate.getFullYear()+1);
var oCookie = encodeURIComponent(name) + '=' + encodeURIComponent(value) + ';expires=' + oDate.toGMTString() + ';path=/';
document.cookie= oCookie;
}
// Read Cookie
'Eat': function (name){
name = name.toLowerCase();
var oCrumbles = document.cookie.split(';');
for(var i=0; i<oCrumbles.length;i++)
{
var oPair= oCrumbles[i].split('=');
var oKey = decodeURIComponent(oPair[0].trim().toLowerCase());
var oValue = oPair.length>1?oPair[1]:'';
if(oKey == name)
return decodeURIComponent(oValue);
}
return '';
}
// Delete / Void Cookie
'Burn': function (name){
Bake(name,'');
}
}
By convention though, you would start your function names with lower case.

Categories

Resources