what is the extname for the file .vimrc - javascript

A question stumbled me around the word extname! Attention please! I'm not ask for a solution, the major point is the word extname.
In the home page of the https://scriptoj.com/, I found a question which demands completing a function called extname, through which input is a filename and output is the extname.
const extname = (filename) => {
/* TODO */
}
when I submitted the code bellow,
const extname = (filename) => {
/* TODO */
var dotIndex = filename.lastIndexOf(".");
var extname = "";
if(dotIndex != -1){
extname = filename.substr(dotIndex);
}
return extname;
}
the error catcher warned me that
if the input is '.hello', the '' should come out but not the '.hello'

if the input is '.hello', the '' should come out but not the '.hello'
Then simply check if dotIndex is not 0 and do not substr the name if this is the case.

Related

Find first file with given filename

Hello I am trying to find first file with given filename ( piece of filename ).
It works fine but it take a while to take result
There is code
const fs = require("fs");
const dirCheckIn =
"\\\\192.168.2.4\\Photos";
exports.checkUploadedFiles = (req, res) => {
let fileName = req.params.filename;
const getAllFiles = function (dirPath, arrayOfFiles) {
files = fs.readdirSync(dirPath);
arrayOfFiles = arrayOfFiles || [];
files.forEach(function (file) {
if (fs.statSync(dirPath + "/" + file).isDirectory()) {
arrayOfFiles = getAllFiles(dirPath + "/" + file, arrayOfFiles);
} else {
arrayOfFiles.push(file);
}
});
return arrayOfFiles;
};
const uploadedFiles = getAllFiles(inventDirCheckIn);
console.log(uploadedFiles)
let result = uploadedFiles.find(
(result) => result.startsWith(fileName));
if (!result) {
res.send('nothing found')
} else if (result) {
res.send(result)
}
}
It works fine but for example if I have over 7000 photos it takes about 5 sec to get result.
Maybe there is smarter solution?
How can I make it in better way? I want to check if file is uploaded into dir Photos.
I got simple api route /api/getUploadedFiles/:filename
Also I want use startsWith because sometimes I do not know full name of file
/**
*
* #param filePath path to file which is to be checked if it exists.
*/
private checkFileExistsSync(filePath: string) {
let flag = true;
try {
fs.accessSync(filePath, fs.constants.F_OK);
} catch (e) {
flag = false;
}
return flag;
}
// Example usage
// path to the file
const dirCheckIn =
"\\\\192.168.2.4\\Photos";
if (checkFileExistsSync(dirCheckIn)) {
// if the file exists do something...
}
if (!checkFileExistsSync(dirCheckIn)) {
// if the file doesn't exists do something...
}

Javascript While Loop Error with User Input

I am just beginning with JS and am having trouble with scope and executing code in similar style as I would with Python. I have started learning JS on Codecademy and have just begun my first project.
My code for the project is below:
//////////////////////////
// R U Hungry Console App
/////////////////////////
// Step 1: Load in Necessary Modules
////////////////////////////////////
// add in the prompt-sync module
// allows to take in and display users name
const prompt = require('prompt-sync')();
// load in fs module
// allows reading in from text files
const fs = require("fs");
// load open module
//allows the opening of webpages
const open = require('open');
// Step 2: Create a menu object
///////////////////////////////
const menu = {
starters: [],
mains: [],
desserts: []
}
// Step 3 Create a factory function to update the Menu object
/////////////////////////////////////////////////////////////
const menuUpdate = (course,dishName,dishLink) => {
if (course.toLowerCase() === 'starter'){
let newItem = {dish: dishName, link: dishLink};
menu.starters.push(newItem);
} else if (course.toLowerCase() === 'main'){
let newItem = {dish: dishName, link: dishLink};
menu.mains.push(newItem);
} else if (course.toLowerCase() === 'dessert'){
let newItem = {dish: dishName, link: dishLink};
menu.desserts.push(newItem);
} else {
console.log('You did not enter a valid course.\nCould not update menu');
}
}
// Step 4: Read in text files of scraped web data
/////////////////////////////////////////////////
const dishes = [menu.starters,menu.mains,menu.desserts];
const filesToRead = ['starters.txt','mains.txt','desserts.txt'];
function addFiles(course,file){
const text = fs.readFileSync(`./menu_files/${file}`);
const textByLine = text.toString().split("\n");
for (const line of textByLine){
course.push(line);
}
}
addFiles(dishes[0],filesToRead[0]);
addFiles(dishes[1],filesToRead[1]);
addFiles(dishes[2],filesToRead[2]);
// Step 5: Put it all together
//////////////////////////////
console.log('\n\nFeeling hungry and can\'t decide what to eat? You have come to the right place.')
const name = prompt('What is your name? ');
console.log(`\nWelcome, ${name}!\nWould you like to be:\n1.Presented With a Menu\n2.Add a Dish to the Menu`);
let userChoice;
while (true){
userChoice = prompt('\nEnter 1 to get a Menu\nEnter 2 to add a Menu Item\nEnter 3 to exit R U Hungry ');
if (userChoice.trim() === 1){
const starterSelector = Math.floor(Math.random() * menu.starters.length);
const mainSelector = Math.floor(Math.random() * menu.mains.length);
const dessertSelector = Math.floor(Math.random() * menu.desserts.length);
let starterDish = menu.starters[starterSelector][0];
let starterRecipe = menu.starters[starterSelector][1];
let mainDish = menu.mains[mainsSelector][0];
let mainRecipe = menu.mains[mainsSelector][1];
let dessertDish = menu.desserts[dessertSelector][0];
let dessertRecipe = menu.desserts[dessertSelector][1];
console.log(`${name}, your Menu is as follows:\n`);
console.log(`Starter: ${starterDish}`);
console.log(`Main: ${mainDish}`);
console.log(`Dessert: ${dessertDish}`);
console.log('\nWe will direct you to recipes for your selected dishes');
// opens the url in the default browser
open(starterRecipe);
open(mainRecipe);
open(dessertRecipe);
} else if (userChoice.trim() === 2){
let userCourse = prompt('Is your dish a Starter, Main or Dessert? ');
let userDishName = prompt('Great! Please tell me the name of your dish ');
let userDishLink = prompt('Please provide the link to the dish recipe ');
menuUpdate = (userCourse,userDishName,userDishLink);
console.log('Menu updated with your dish!');
} else {
console.log(`Goodbye, ${name}.`);
break;
}
console.log('Would you like to perform another function?');
}
// End
I am having trouble with the while loop at the end.
This part specifically:
let userChoice;
while (true){
userChoice = prompt('\nEnter 1 to get a Menu\nEnter 2 to add a Menu Item\nEnter 3 to exit R U Hungry ');
if (userChoice.trim() === 1){
const starterSelector = Math.floor(Math.random() * menu.starters.length);
const mainSelector = Math.floor(Math.random() * menu.mains.length);
const dessertSelector = Math.floor(Math.random() * menu.desserts.length);
let starterDish = menu.starters[starterSelector][0];
let starterRecipe = menu.starters[starterSelector][1];
let mainDish = menu.mains[mainsSelector][0];
let mainRecipe = menu.mains[mainsSelector][1];
let dessertDish = menu.desserts[dessertSelector][0];
let dessertRecipe = menu.desserts[dessertSelector][1];
console.log(`${name}, your Menu is as follows:\n`);
console.log(`Starter: ${starterDish}`);
console.log(`Main: ${mainDish}`);
console.log(`Dessert: ${dessertDish}`);
console.log('\nWe will direct you to recipes for your selected dishes');
// opens the url in the default browser
open(starterRecipe);
open(mainRecipe);
open(dessertRecipe);
} else if (userChoice.trim() === 2){
let userCourse = prompt('Is your dish a Starter, Main or Dessert? ');
let userDishName = prompt('Great! Please tell me the name of your dish ');
let userDishLink = prompt('Please provide the link to the dish recipe ');
menuUpdate = (userCourse,userDishName,userDishLink);
console.log('Menu updated with your dish!');
} else {
console.log(`Goodbye, ${name}.`);
break;
}
console.log('Would you like to perform another function?');
}
It keeps executing the code in the else block and then exiting the program.
In python I would have used something like this:
while (True):
choice = input("What is your name? ")
if choice.strip().lower() != 'john':
print("Who are you?")
break;
elif choice choice.strip().lower() != 'shaun':
print("Who are you?")
break;
else:
print("Hi there, glad you aren't John or Shaun")
continue
Stupid example but I just wanted to show how I could normally have achieved something like this before.
Would anyone be able to explain what is incorrect?
I also struggle to understand the scope in JS. Is that perhaps the problem here?
I am finding it difficult in some cases to apply my thinking from Python to JS.
Any help would be appreciated. I am really wanting to learn.
Thanks!
Maybe as a starter you can you == rather than === as it would not match the type, also in your else if it seems you are calling function incorrectly, remove =.

How can I overwrite and append data to the same file multiple times in node js

I have a "clients.txt" file where I have a list of emails. I try to run a program for sending emails where I chose a number of emails to use from the file, in that case the number is 2. After I use the two emails I want to overwrite "clients.txt" without them. The problem is when I try to run the code just for one single time every thing is working! but if I make a loop something is wrong. Looking forward to see any help from you guys. Thanks! I add the code bellow. PS: Sorry for my bad english!
function readEmails(){
const fs = require('fs');
clients_list = fs.readFileSync('clients.txt', 'utf8').split('\n');
let filtered = clients_list.filter(function (el) {
return el != null && el != '';
});
return filtered
}
function dump_array(arr, file){
let fs = require('fs');
let file = fs.createWriteStream(file);
file.on('error', function(err) { /* error handling */ });
arr.forEach(function(v) { file.write(v + '\n'); });
file.end();
}
while_var = 0;
while (while_var < 2){
while_var ++;
let all_clients = readEmails();
let selected_clients = [];
if (all_clients.length > 0){
selected_clients = all_clients.splice(0,2);
dump_array(all_clients, 'clients.txt');
console.log(selected_clients);
}else{
console.log('No more clients')
}
}
const fs = require('fs');
function readEmails(){
const clients_list = fs.readFileSync('clients.txt', 'utf8').split('\n');
const filtered = clients_list
// clear false, 0 and undefined too
.filter(el => !!el)
// remove extra spaces and \r symbols
.map(el => el.trim());
return filtered;
}
function dump_array(arr, file){
// Here you need sync method.
fs.writeFileSync(file, arr.join('\n'));
// And here was 'already declared' error in orginal code
}
let while_var = 0;
while (while_var++ < 2){
let all_clients = readEmails();
let selected_clients = [];
if (all_clients.length > 0){
selected_clients = all_clients.splice(0,2);
dump_array(all_clients, 'clients.txt');
console.log(selected_clients);
}else{
console.log('No more clients')
}
}

Change the way my nodejs app activates

The code listed below searches for files that contains a specified string under it's directory/subdirectories.
to activate it, you type node [jsfilename] [folder] [ext] [term]
i would like to change it so it will search without the base folder, i don't want to type ./ , just node [jsfilename] [ext] [term]
so it already know to search from it's location.
i know it has something to do with the process.argv but it need a hint what should i do.
PS:.
I already tried to change the last raw to :
searchFilesInDirectory(__dirname, process.argv[3], process.argv[2]);
it giving me noting...
const path = require('path');
const fs = require('fs');
function searchFilesInDirectory(dir, filter, ext) {
if (!fs.existsSync(dir)) {
console.log(`Welcome! to start, type node search [location] [ext] [word]`);
console.log(`For example: node search ./ .txt myterm`);
return;
}
const files = fs.readdirSync(dir);
const found = getFilesInDirectory(dir, ext);
let printed = false
found.forEach(file => {
const fileContent = fs.readFileSync(file);
const regex = new RegExp('\\b' + filter + '\\b');
if (regex.test(fileContent)) {
console.log(`Your word has found in file: ${file}`);
}
if (!printed && !regex.test(fileContent)) {
console.log(`Sorry, Noting found`);
printed = true;
}
});
}
function getFilesInDirectory(dir, ext) {
if (!fs.existsSync(dir)) {
console.log(`Specified directory: ${dir} does not exist`);
return;
}
let files = [];
fs.readdirSync(dir).forEach(file => {
const filePath = path.join(dir, file);
const stat = fs.lstatSync(filePath);
if (stat.isDirectory()) {
const nestedFiles = getFilesInDirectory(filePath, ext);
files = files.concat(nestedFiles);
} else {
if (path.extname(file) === ext) {
files.push(filePath);
}
}
});
return files;
}
searchFilesInDirectory(process.argv[2], process.argv[4], process.argv[3]);
If I get what are you trying to achieve. You can do so by slightly changing your function call in the last line.
Change
searchFilesInDirectory(process.argv[2], process.argv[4], process.argv[3]);
to
searchFilesInDirectory(process.cwd(), process.argv[3], process.argv[2]);
Edit
As #Keith said in comments use process.cwd() to get the current working directory instead of __dirname
If you want it to work for both conditions then you need to do a conditional check...
if(process.argv.length === 5){
searchFilesInDirectory(process.argv[2], process.argv[4], process.argv[3]);
}else if(process.argv.length === 4){
searchFilesInDirectory(process.cwd(), process.argv[3], process.argv[2]);
}else{
throw new Error("Not enough arguments provided..");
}

Javascript,nodejs: give a "string not found" messege on console.log

The code listed below searches for files that
contains a specified string under it's directory/subdirectories.
to activate it, you type node [jsfilename] [folder] [filename] [ext]
i would also like it to announce: Nothing found in a console.log every time that
a word wasn't found.
ive tried
if (!regex.test(fileContent)) {
console.log(`Noting found`);
it works only if you have one file without your word, but if not ,it loops.
for example if you have 4 files and one of them has the string it wil show
Your word was found in directory: [file]
Noting found
Noting found
Noting found.
So, how can i stop the loop after one !found console.log and how can i prevent it from showing in case of something has found?
const path = require('path');
const fs = require('fs');
function searchFilesInDirectory(dir, filter, ext) {
if (!fs.existsSync(dir)) {
console.log(`Specified directory: ${dir} does not exist`);
return;
}
const files = fs.readdirSync(dir);
const found = getFilesInDirectory(dir, ext);
found.forEach(file => {
const fileContent = fs.readFileSync(file);
const regex = new RegExp('\\b' + filter + '\\b');
if (regex.test(fileContent)) {
console.log(`Your word was found in directory: ${file}`);
}
});
}
function getFilesInDirectory(dir, ext) {
if (!fs.existsSync(dir)) {
console.log(`Specified directory: ${dir} does not exist`);
return;
}
let files = [];
fs.readdirSync(dir).forEach(file => {
const filePath = path.join(dir, file);
const stat = fs.lstatSync(filePath);
if (stat.isDirectory()) {
const nestedFiles = getFilesInDirectory(filePath, ext);
files = files.concat(nestedFiles);
} else {
if (path.extname(file) === ext) {
files.push(filePath);
}
}
});
return files;
}
searchFilesInDirectory(process.argv[2], process.argv[3], process.argv[4]);
Change:
if (!regex.test(fileContent)) {
console.log(`Noting found`);
// ...
to:
if (!printed && !regex.test(fileContent)) {
console.log(`Noting found`);
printed = true;
// ...
and make sure that you have a variable called printed defined in outer scope, originally falsy.

Categories

Resources