I try to write a code that will create a file with an amount of random jokes using this npm and Environment Variables in an env file but I can't get it to work.
here is the code:
let oneLinerJoke = require("one-liner-joke");
require("dotenv").config();
let fs = require("fs");
var getRandomJokeWithTag = oneLinerJoke.getRandomJokeWithTag(
`${process.env.JOKE_SUBJECT}`
);
let arrayJokes = [];
let i = 0;
let counter = 0;
let amount = parseInt(`${process.env.JOKE_AMOUNT}`);
while (i <= amount) {
let joke = oneLinerJoke.getRandomJokeWithTag(process.env.JOKE_SUBJECT);
joke = joke.body.replace(",", "");
if (arrayJokes.includes(joke)) {
arrayJokes.push((joke + "\n"));
i++;
}
}
const createFile = fs.writeFileSync('./created_files/jokes.txt', arrayJokes.toString().replace(/,/g, ""));
Add __dirname to specify the directory.
const createFile = fs.writeFileSync(__dirname + '/created_files/jokes.txt', arrayJokes.toString().replace(/,/g, ""));
Related
const handleFileReader = (event) => {
var theFiles = event.target.files;
for (var i = 0; i < theFiles.length; i++) {
var item = document.createElement("li");
item.innerHTML = theFiles[i].webkitRelativePath;
var div_element = document.body.appendChild(item);
console.log(div_element);
var path = theFiles[i].webkitRelativePath.split("/").slice(0, -1).join("/") + "/";
console.log(path); //folder path
var splitUrl = path.split('/');
console.log(splitUrl);
const extractFilename = (path) => {
const pathArray = path.split("/");
const lastIndex = pathArray.length - 1;
return pathArray[lastIndex];
};
console.log(extractFilename(theFiles[i].webkitRelativePath));
};
I have splitting the folders,sub-folders and files seperatly and adding folders name inside array structure.
How i can manage that array for sub-folders and files inside it?
please refer to the code below:
function getGdriveLinks() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheetByName('Test');
const fileNames = sheet.getRange('C2:C').getValues();
const mainFolder = DriveApp.getFolderById('Folder ID');
for (var i = 0; i < fileNames.filter(String).length; i++){
var fileName = fileNames[i][0].toString();
var fileLink = getGdriveLink(fileName,mainFolder);
Logger.log(fileLink);
}
}
function getGdriveLink(searchFileName,folder){
var mainFiles = folder.getFiles();
while (mainFiles.hasNext()){
var file = mainFiles.next();
if(file.getName().indexOf(searchFileName) != -1){
Logger.log(file.getUrl());
return file.getUrl();
}
}
var subFolders = folder.getFolders();
while (subFolders.hasNext()){
var subFolder = subFolders.next();
getGdriveLink(searchFileName,subFolder);
}
}
Basically, the aim is to get the filenames in C2:C of Test sheet, find each of these in the 'Folder ID', and then return their URL. The URL is returned correctly when I log it from getGdriveLink(searchFileName,folder) using Logger.log(file.getUrl()). However, it returns null via the Logger.log(fileLink) when the result goes back to getGdriveLinks() function. Is there anything I'm missing? We're using a corporate domain if that's something to consider. Hoping for your guidance. Thanks!
You could also do it this way and avoid recursion altogether
function getPathAllDrivesFromId(fileid) {
var ids = [{id:fileid,name:DriveApp.getFileById(fileid).getName()}];
let r;
do {
r = Drive.Files.get(fileid,{supportsAllDrives:true,supportsTeamDrives:true});
if(r.parents.length > 0) {
//Logger.log(JSON.stringify(r.parents[0]));
ids.push({id:r.parents[0].id,name:DriveApp.getFolderById(r.parents[0].id).getName()});
fileid = r.parents[0].id
}
}while (r.parents.length > 0);
if(ids[ids.length - 1].name == "Drive") {
ids[ids.length - 1].name = Drive.Drives.get(ids[ids.length - 1].id).name;
}
//Logger.log(JSON.stringify(ids));
let path = ids.map(obj => obj.name).flat().reverse().join(' / ')
//Logger.log(path);
return path;
}
function getGdriveLinks() {
const ss = SpreadsheetApp.getActive();
const sh = ss.getSheetByName('Test');
const osh = ss.getSheetByName("Results");
const ns = sh.getRange('C2:C' + sh.getLastRow()).getValues();
const folder = DriveApp.getFolderById('Folder ID');
const result = [["Filename", "Id", "Url", "path"]];
ns.forEach(n => {
let files = DriveApp.getFilesByName(n);
while (files.hasNext()) {
let file = files.next();
let path = getPathAllDrivesFromId(file.getId());
if (~path.indexOf(folder.getName())) {
result.push([file.getName(), file.getId(), file.getUrl(), path]);
}
}
})
osh.clearContents();
osh.getRange(1, 1, result.length, result[0].length).setValues(result);
}
I'm new to JS so I have been writing code the most simple way possible for me just to get the functionality that I want the plan being clean it up and shorten everything later.
Part of doing this I have loads of classes to select a series of elements by their id. Is it possible to put these in an array? all the elements are numbered 1-12
Essentially I have three items to get a slide its accompanying audio and subtitle
const slide0 = document.getElementById("slide0");
const slide1 = document.getElementById("slide1");
const slide2 = document.getElementById("slide2");
const slide3 = document.getElementById("slide3");
const slide4 = document.getElementById("slide4");
const slide5 = document.getElementById("slide5");
const slide6 = document.getElementById("slide6");
const slide7 = document.getElementById("slide7");
const slide8 = document.getElementById("slide8");
const slide9 = document.getElementById("slide9");
const slide10 = document.getElementById("slide10");
const slide11 = document.getElementById("slide11");
const slide12 = document.getElementById("slide12");
const subt1 = document.getElementById("sub1");
const subt2 = document.getElementById("sub2");
const subt3 = document.getElementById("sub3");
const subt4 = document.getElementById("sub4");
const subt5 = document.getElementById("sub5");
const subt6 = document.getElementById("sub6");
const subt7 = document.getElementById("sub7");
const subt8 = document.getElementById("sub8");
const subt9 = document.getElementById("sub9");
const subt10 = document.getElementById("sub10");
const subt11 = document.getElementById("sub11");
const subt12 = document.getElementById("sub12");
const chp1 = document.getElementById("audiochp1");
const chp2 = document.getElementById("audiochp2");
const chp3 = document.getElementById("audiochp3");
const chp4 = document.getElementById("audiochp4");
const chp5 = document.getElementById("audiochp5");
const chp6 = document.getElementById("audiochp6");
const chp7 = document.getElementById("audiochp7");
const chp8 = document.getElementById("audiochp8");
const chp9 = document.getElementById("audiochp9");
const chp10 = document.getElementById("audiochp10");
const chp11 = document.getElementById("audiochp11");
const chp12 = document.getElementById("audiochp12");
Yes, you can. For example:
let slides = [];
for (let i = 0; i < num_slides; i++) {
slides.push({
slide: document.getElementById(`slide${i}`),
subt: document.getElementById(`sub${i}`),
chp: document.getElementById(`audiochp${i}`)
});
}
You could, however, also do something similar by giving your elements classes and then using document.getElementsByClassName('slide') and so on.
Surely! I highly advise you to generate a few helper functions for this. Take a look at the following example:
function getSlides(theMaxSlideNumer) {
const returnElements = [];
for (int i = 0; i <= theMaxSlideNumber; i++) {
const aSlideQuery = "#slide" + i.toString();
returnElements.push(document.querySelector(aSlideQuery));
}
return returnElements;
}
const slides = getSlides(12);
Add safeguard
function getSlides(theMaxSlideNumer) {
const returnElements = [];
for (int i = 0; i <= theMaxSlideNumber; i++) {
const aSlideQuery = "slide" + i.toString();
returnElements.push(document.querySelector(aSlideQuery));
}
returnElements.forEach((aElement)=>{
if (aElement === null) console.warn("A dom element could not be found, trace this message!");
});
return returnElements;
}
const slides = getSlides(12);
Target them using querySelectorAll and spread them into an array.
[...document.querySelectorAll('[id^=slide]')] // CSS selector that captures all elements starting with slide word
Repeat for each group you have.
Fiddle: https://jsfiddle.net/dk9f86rp/19/
I have .log file and I need to get this file in javascript and convert to JSON. I try this
var j= readTextFile("log991/sensorData.log");
console.log(j);
var jsonnn = JSON.stringify(j);
console.log(jsonnn);
But I only get path in console log. Is there any way to make this?
this is how .log file looks
2018-04-03 15:47:58,873 INFO log(17) batteryCurrent=-0.45, solarCurrent=3.27,
hybridCurrent=0, batteryVoltage=12.88, solarVoltage=13.09
2018-04-03 15:48:00,074 INFO log(17) batteryCurrent=-0.45, solarCurrent=3.27,
hybridCurrent=0, batteryVoltage=12.88, solarVoltage=13.09
2018-04-03 15:48:01,274 INFO log(17) batteryCurrent=-0.4, solarCurrent=3.28,
hybridCurrent=0, batteryVoltage=12.89, solarVoltage=13.1
thnx
try this code used synchronous version
const fs = require('fs');
var text = fs.readFileSync('/somepath/a.txt','utf8')
console.log (text)
try this code to convert into json
const fs = require('fs');
var text = fs.readFileSync('/somepath/a.txt','utf8')
array = text.split("\n")
var dataArray = [];
for(var i=0; i<array.length; i++){
if(array[i] == ''){continue}
let tempArray = []
tempArray = array[i].split(",");
dataArray.push(tempArray)
};
json = {};
var c = 1;
dataArray.forEach( (e1) =>{
isdate = true;
var tempjson = {};
e1.forEach( (e2) =>{
var key;
if(isdate ) {
key = 'date';
tempjson[key] = e2;
isdate = false;
}
else if(e2.includes("batteryCurrent")){
key = "batteryCurrent";
tempjson[key]= e2.split("batteryCurrent=")[1]
}
else{
var arr = e2.split("=");
key = arr[0].trim();
tempjson[key] = arr[1];
}
})
json[c] = tempjson;
c++
});
console.log(json)
Are you using node?
const fs = require('fs')
fs.readFile('log991/sensorData.log', 'utf8', (err, data) => {
console.log(data)
}
Use the readFile method of fs module.
var fs = require('fs')
fs.readFile('log991/sensorData.log', 'utf8', function(err, data) {
console.log(data)
});
Ok, i fix this with python
import json
a = open('log991/sensorData.log','r')
text = a.read()
text_as_list = text.split('\n')
keys = text_as_list[2].split()
result = []
for item in text.split('\n')[4:len(text_as_list)]:
temp_dict = {}
for i,j in zip(keys,item.split()):
if j.isdigit():
temp_dict[i] = int(j)
else:
temp_dict[i] = j
result.append(temp_dict)
print (json.dumps(result))
I'm trying to log an array of numerically named sub-directories in "e:\subdirectory\" by using fs.statSync but I keep getting the error "module.exports" is not a function; to my understanding, this is exactly how I'm supposed to export the data
I'm using the synchronous version because I want the array to finish populating before it's exported.
this is for a "proof of concept", I plan on serving an html doc and pushing this array to an input field
here is the code...
checke.js
var fs = require('fs');
function checkE() {
for (var i = 1, accts = [], path = "e:\\subdirectory\\"; i <10000; i++ ) {
var target = fs.statSynch(path + i.toString())
if (target.isDirectory()) { accts.push(i) }
}
}
module.exports(checkE)
init.js
var checke = require('./checke.js')
console.log(checke)
You need to assign something to module.exports not call it like a function. module.exports is an object
checke.js
var fs = require('fs');
module.exports = {
checkE: function checkE() {
var accts = [];
var path = 'e:\\subdirectory\\';
for (var i = 1; i <10000; i++ ) {
var target = fs.statSync(path + i.toString())
if (target.isDirectory())
accts.push(i);
}
return accts;
}
}
init.js
var checke = require('./checke.js');
checke.checkE();