Is it possible (and how) to create a file path if I know part of file pathname?
For example I have file pathname /User/Documents/Italy/Report_123.pdf
How to complete pathname if I know there is pdf in folder Italy which contain word Report_ those numbers at the end are dynamic?
I need to complete this task in javascript. Thanks in advance.
if you're using node.js, you can get all the files from that folder, then you iterate that result array to get the one you want.
import { readdir } from 'fs/promises';
const result = await readdir('C:/User/Documents/Italy');
console.log(result);
use this it may be helps you
var documentName = "Report_123.pdf"; // Use documentName Variable to use other js functions for example - documentName.split("_").
var path = "../User/Documents/Italy/"+documentName;
Related
In a react project I am trying to list all the files in blob storage using a sas token created for the given directory. My understanding is I need to create a DataLakeFileSystemClient but I only have a url for the directory and a DataLakeDirectoryClient and somehow need to create the DataLakeFileSystemClient.
The url passed is something along the lines of: https://myaccount.dfs.core.windows.net/mycontainer/mydirectory{sastoken}
I have found a way to do this, although I don't know if it's the best way.
To get the directory client to a FileSystem client I wrote a helper method
const getFileSystemClient = (directoryClient: DataLakeDirectoryClient) => {
const url = new URL(directoryClient.url);
url.pathname = directoryClient.fileSystemName;
return new DataLakeFileSystemClient(url.toString());
}
To list directories I use the following code
const fsClient = getFileSystemClient(directoryClient);
for await(const path of fsClient.listPaths({path: directoryClient.name})) {
console.log(path.name);
}
I'm trying to write in a text file, but not at the end like appendFile() do or by replacing the entiere content...
I saw it was possible to chose where you want to start with start parameter of fs.createwritestream() -> https://nodejs.org/api/fs.html#fs_fs_createwritestream_path_options
But there is no parameter to say where to stop writting, right ? So it remove all the end of my file after I wrote with this function.
const fs = require('fs');
var logger = fs.createWriteStream('result.csv', {
flags: 'r+',
start: 20 //start to write at the 20th caracter
})
logger.write('5258,525,98951,0,1\n') //example a new line to write
Is there a way to specify where to stop writting in the file to have something like:
....
data from begining
....
5258,525,98951,0,1
...
data till the end
...
I suspect you mean, "Is it possible to insert in the middle of the file." The answer to that is: No, it isn't.
Instead, to insert, you have to:
Determine how big what you're inserting is
Copy the data at your insertion point to that many bytes later in the file
Write your data
Obviously when doing #2 you need to be sure that you're not overwriting data you haven't copied yet (either by reading it all into memory first or by working in blocks, from the end of the file toward the insertion point).
(I've never looked for one, but there may be an npm module out there that does this for you...)
You could read/parse your file at first. Then apply the modifications and save the new file.
Something like:
const fs = require("fs");
const fileData = fs.readFileSync("result.csv", { encoding: "utf8" });
const fileDataArray = fileData.split("\n");
const newData = "5258,525,98951,0,1";
const index = 2; // after each row to insert your data
fileDataArray.splice(index, 0, newData); // insert data into the array
const newFileData = fileDataArray.join("\n"); // create the new file
fs.writeFileSync("result.csv", newFileData, { encoding: "utf8" }); // save it
With the new Firebase API you can upload files into cloud storage from client code. The examples assume the file name is known or static during upload:
// Create a root reference
var storageRef = firebase.storage().ref();
// Create a reference to 'mountains.jpg'
var mountainsRef = storageRef.child('mountains.jpg');
// Create a reference to 'images/mountains.jpg'
var mountainImagesRef = storageRef.child('images/mountains.jpg');
or
// File or Blob, assume the file is called rivers.jpg
var file = ...
// Upload the file to the path 'images/rivers.jpg'
// We can use the 'name' property on the File API to get our file name
var uploadTask = storageRef.child('images/' + file.name).put(file);
With users uploading their own files, name conflicts are going to be an issue. How can you have Firebase create a filename instead of defining it yourself? Is there something like the push() feature in the database for creating unique storage references?
Firebase Storage Product Manager here:
TL;DR: Use a UUID generator (in Android (UUID) and iOS (NSUUID) they are built in, in JS you can use something like this: Create GUID / UUID in JavaScript?), then append the file extension if you want to preserve it (split the file.name on '.' and get the last segment)
We didn't know which version of unique files developers would want (see below), since there are many, many use cases for this, so we decided to leave the choice up to developers.
images/uuid/image.png // option 1: clean name, under a UUID "folder"
image/uuid.png // option 2: unique name, same extension
images/uuid // option 3: no extension
It seems to me like this would be a reasonable thing to explain in our documentation though, so I'll file a bug internally to document it :)
This is the solution for people using dart
Generate the current date and time stamp using:-
var time = DateTime.now().millisecondsSinceEpoch.toString();
Now upload the file to the firebase storage using:-
await FirebaseStorage.instance.ref('images/$time.png').putFile(yourfile);
You can even get the downloadable url using:-
var url = await FirebaseStorage.instance.ref('images/$time.png').getDownloadURL();
First install uuid - npm i uuid
Then define the file reference like this
import { v4 as uuidv4 } from "uuid";
const fileRef = storageRef.child(
`${uuidv4()}-${Put your file or image name here}`
);
After that, upload with the file with the fileRef
fileRef.put(Your file)
In Android (Kotlin) I solved by combining the user UID with the milliseconds since 1970:
val ref = storage.reference.child("images/${auth.currentUser!!.uid}-${System.currentTimeMillis()}")
code below is combination of file structure in answer from #Mike McDonald , current date time stamp in answer from # Aman Kumar Singh , user uid in answer from #Damien : i think it provides unique id, while making the firebase storage screen more readable.
Reference ref = firebaseStorage
.ref()
.child('videos')
.child(authController.user.uid)
.child(DateTime.now().millisecondsSinceEpoch.toString());
Using JSZip, is there a way to edit a file within a zipped file?
I've tried looking for solutions and going through the API but I can't seem to find a solution.
Any help with this would be great! Thanks in advance!
You can edit a file inside your zip with .file method.
zip.file("existing_filename", "new file content");
This method is used for adding and updating file content.
Just make sure the file already exist.
You can read more about it in the documentation.
You can refer to the official documentation.
And here's a more complete Node.js example:
var fs = require("fs");
var JSZip = require("jszip");
async function zipDemo() {
// read the existing zip file
var zipData = fs.readFileSync("input.zip");
var zip = await JSZip.loadAsync(zipData);
// add a new JSON file to the zip
zip.file("sample.json", JSON.stringify({demo:123}));
// write out the updated zip
zip.generateNodeStream({type:'nodebuffer', streamFiles:true})
.pipe(fs.createWriteStream('output.zip'))
.on('finish', function () {
console.log("output`enter code here`.zip written.");
});
}
zipDemo();
How to get the directory of a file?
For example, I pass in a string
C:\Program Files\nant\bin\nant.exe
I want a function that returns me
C:\Program Files\nant\bin
I would prefer a built in function that does the job, instead of having manually split the string and exclude the last one.
Edit: I am running on Windows
I don't know if there is any built in functionality for this, but it's pretty straight forward to get the path.
path = path.substring(0,path.lastIndexOf("\\")+1);
If you use Node.js, path module is quite handy.
path.dirname("/home/workspace/filename.txt") // '/home/workspace/'
Use:
var dirname = filename.match(/(.*)[\/\\]/)[1]||'';
*The answers that are based on lastIndexOf('/') or lastIndexOf('\') are error prone, because path can be "c:\aa/bb\cc/dd".
(Matthew Flaschen did took this into account, so my answer is a regex alternative)
There's no perfect solution, because this functionality isn't built-in, and there's no way to get the system file-separator. You can try:
path = path.substring(0, Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\")));
alert(path);
Path module has an inbuilt function
Yes, the inbuilt module path has dirname() function, which would do the job for you.
const path = require("path");
file_path = "C:\\Program Files\\nant\\bin\\nant.exe" \\windows path
file_path = "C:/Program Files/nant/bin/nant.exe" \\linux path
path.dirname(file_path); \\gets you the folder path based on your OS
I see that your path is neither windows nor Linux compatible. Do not hardcode path; instead, take a reference from a path based on your OS.
I generally tackle such situations by creating relative paths using path.join(__dirname, "..", "assets", "banner.json");.
This gives me a relative path that works regardless of the OS you are using.
function getFileDirectory(filePath) {
if (filePath.indexOf("/") == -1) { // windows
return filePath.substring(0, filePath.lastIndexOf('\\'));
}
else { // unix
return filePath.substring(0, filePath.lastIndexOf('/'));
}
}
console.assert(getFileDirectory('C:\\Program Files\\nant\\bin\\nant.exe') === 'C:\\Program Files\\nant\\bin');
console.assert(getFileDirectory('/usr/bin/nant') === '/usr/bin');
Sorry to bring this back up but was also looking for a solution without referencing the variable twice. I came up with the following:
var filepath = 'C:\\Program Files\\nant\\bin\\nant.exe';
// C:\Program Files\nant\bin\nant.exe
var dirpath = filepath.split('\\').reverse().splice(1).reverse().join('\\');
// C:\Program Files\nant\bin
This is a bit of a walk through manipulating a string to array and back but it's clean enough I think.
filepath.split("/").slice(0,-1).join("/"); // get dir of filepath
split string into array delimited by "/"
drop the last element of the array (which would be the file name + extension)
join the array w/ "/" to generate the directory path
such that
"/path/to/test.js".split("/").slice(0,-1).join("/") == "/path/to"
And this?
If isn't a program in addressFile, return addressFile
function(addressFile) {
var pos = addressFile.lastIndexOf("/");
pos = pos != -1 ? pos : addressFile.lastIndexOf("\\");
if (pos > addressFile.lastIndexOf(".")) {
return addressFile;
}
return addressFile.substring(
0,
pos+1
);
}
console.assert(getFileDirectory('C:\\Program Files\\nant\\bin\\nant.exe') === 'C:\\Program Files\\nant\\bin\\');
console.assert(getFileDirectory('/usr/bin/nant') === '/usr/bin/nant/');
console.assert(getFileDirectory('/usr/thisfolderhaveadot.inhere') === '/usr/');
The core Javascript language doesn't provide file/io functions. However if you're working in a Windows OS you can use the FileSystemObject (ActiveX/COM).
Note: Don't use this in the client script-side script of a web application though, it's best in other areas such as in Windows script host, or the server side of a web app where you have more control over the platform.
This page provides a good tutorial on how to do this.
Here's a rough example to do what you want:
var fso, targetFilePath,fileObj,folderObj;
fso = new ActiveXObject("Scripting.FileSystemObject");
fileObj = fso.GetFile(targetFilePath);
folderObj=fileObj.ParentFolder;
alert(folderObj.Path);