I'm working with node.js and looking for some examples and best practices around:
Creating a folder named test_folder
Adding a new file to that folder, named test.txt
Adding the text HI to test.txt
following is the code to create a folder and then create a file inside it with some text.
let fs = require('fs');
let dir = './test_folder'; //name of the directory/folder
if (!fs.existsSync(dir)){ //check if folder already exists
fs.mkdirSync(dir); //creating folder
}
fs.writeFile("./test_folder/test.txt", "HI", function(err) { //creating file test.txt inside test_folder with HI written on it
if(err) {
return console.log(err);
}
console.log("The file is saved!");
});
Related
I am having JavaScript file under menu directory in the root menu.js. I want to rename JavaScript file menu.js to menuOLD.js under same directory onClick.
I would have googled and found small sample as :
function renamefile(){
const myFile = new File(['hello-world'], 'my-file.txt');
const myRenamedFile = new File([myFile], 'my-file-final-1-really.txt');
console.log(myRenamedFile);
}
I have checked it's output in Console and got below output:
It's working.
But I would need to rename excatly menu.js file under menu directory.
How should I do this?
With Node.js
const fs = require('fs');
fs.rename('menu.js', 'menuOLD.js', (err) => {
console.log(err);
});
See here:
My code is as below. The contents of the file is a simple "hello world" I have the hello.docx file in the same folder I am calling this mammoth function.
Error result: fatal Error: ENOENT: no such file or directory, open './hello.docx'
Any idea what I am doing wrong? I am using this in my express node route
mammoth.extractRawText({path: "./hello.docx"})
.then(function(result){
var text = result.value; // The raw text
console.log(text);
// var messages = result.messages;
})
.done();
It seems clear by the error displayed that the directory or file cannot be read. How are you uploading your file? If you are uploading your docx file using multer, you need to provide a reference to the file uploaded inside the path or buffer option as such:
mammoth.extractRawText({buffer: variable_that_holds_the_file.buffer})
.then(function(result){
var text = result.value; // The raw text
console.log(text);
})
.done();
Else, you need to revise the path since it may not be correct.
To test this, use __dirname and or __filename in your console.log inside multer to see where your path is.
use below code it might help you. it worked for me.
const mammoth = require("mammoth");
const path = require("path");
let filePath = path.join(__dirname,'./sampledocxfile.docx');
mammoth.extractRawText({path: filePath})
.then(function(result){
var html = result.value;
var messages = result.messages;
console.log(html);
})
.done();
I currently have a Zapier process running that automatically creates 3 new files uploaded from a form into a folder in my Google Drive called "New Users". Each file is formatted as firstname_lastname-filename.ext but this is not good in terms of organization.
Instead, I would like to dynamically create a new folder labeled as firstname_lastname containing the 3 new files every time they come in with the same firstname_lastname, rather than having a generic "New Users" folder filled with hundreds or thousands of files.
Unfortunately I'm a pretty novice programmer, so I'm not quite sure how to go about this using Apps Script.
Any advice?
I've thought about something like:
var files = DriveApp.getFiles();
while (files.hasNext()) {
var file = files.next();
Logger.log(file.getName());
if file.getName().includes("firstname_lastname") { // Check if a file name contains the string firstname_lastname
var folders = DriveApp.getFolders();
while (folders.hasNext()) {
var folder = folders.next();
Logger.log(folder.getName());
if folder.getName().includes("firstname_lastname") { // Check if a folder exists with a name that contains the string firstname_lastname
makeCopy(file.getName(), folder.getName()) // if said folder exists, make a copy of the the file and move it to that folder
} else { // if said folder does not exist...
var newFolderName = file.getName() // let the newFolderName be the same name as the file (I know this isn't right if I want the folder name to be firstname_lastname without the actual uploaded file name plus extension)
createFolder(newFolderName); // then create a folder that has the name newFolderName
makeCopy(file.getName(), folder.getName(newFolderName)) // then make a copy of the file and put it into the folder
}
}
}
}
You may want to first establish your root folder, "New Users". I've created a snippet for the flow:
//New Users Folder
var rootFolder = DriveApp.getFolderById("FOLDER_ID");
function myFunction() {
var files = rootFolder.getFolders();
while (files.hasNext()) {
var file = files.next();
Logger.log(file.getName());
if(file.getName() == fileuploadName){
//copy file if folder is existing
file.addFile(child)
}
else{
//create folder
var newFolder = rootFolder.addFolder(child);
newFolder.addFile(child)
}
}
Logger.log("Done")
}
This flow should be ok when you want to implement a dynamic creation of folder then migrate the files to a specific folder name.
Hope this helps.
I am attempting to zip the contents of two directories and download the resulting .zip file. One directory contains .txt files and the other .jpg. I am using archiver to zip the files and running the express framework on node js. I am inclined to think that the problem exists in the download step, as the resulting zipped file that is created in the project root expands as expected, however when the file is downloaded, I get an "Error 2 - No such file or directory."
app.get('/download',function(req, res){
zipFile = new Date() + "-Backup.zip";
var output = fs.createWriteStream(__dirname +"/backups/"+ zipFile);
var archive = archiver('zip');
output.on('close', function() {
console.log(archive.pointer() + ' total bytes');
console.log('archiver has been finalized and the output file descriptor has closed.');
});
archive.on('error', function(err) {
throw err;
});
archive.pipe(output);
var files1 = fs.readdirSync(__dirname+'/posts');
var files2 = fs.readdirSync(__dirname+'/uploads');
for(var i = 0; i< files1.length; i++){
archive.append(fs.createReadStream(__dirname+"/posts/"+files1[i]), { name: files1[i] });
}
for(var i = 0; i< files2.length; i++){
archive.append(fs.createReadStream(__dirname+"/uploads/"+files2[i]), { name: files2[i] });
}
archive.finalize();
res.download(__dirname + "/backups/" + zipFile, zipFile);
});
zipFile is a global variable.
The on 'close' logs fire properly and no errors occur, but the file will not open after being downloaded. Is there an issue with response headers or something else I am unaware of?
Thanks for the help.
I solved my own problem using node-zip as the archive utility.
var zip = require('node-zip')(); // require the node-zip utility
var fs = require('fs'); // I use fs to read the directories for their contents
var zipName = "someArbitraryName.zip"; // This just creates a variable to store the name of the zip file that you want to create
var someDir = fs.readdirSync(__dirname+"/nameOfDirectoryToZip"); // read the directory that you would like to zip
var newZipFolder = zip.folder('nameOfDirectoryToZip'); // declare a folder with the same name as the directory you would like to zip (we'll later put the read contents into this folder)
//append each file in the directory to the declared folder
for(var i = 0; i < someDir.length,i++){
newZipFolder.file(someDir[i], fs.readFileSync(__dirname+"/nameOfDirectoryToZip/"+someDir[i]),{base64:true});
}
var data = zip.generate({base64:false,compression:'DEFLATE'}); //generate the zip file data
//write the data to file
fs.writeFile(__dirname +"/"+ zipName, data, 'binary', function(err){
if(err){
console.log(err);
}
// do something with the new zipped file
}
Essentially, what is happening can broken down into 3 steps:
Use fs to read the contents of a directory that you would like to zip.
Use zip.folder to declare the folder, then use zip.file to append files to that directory. I just used a for loop to iteratively add each file in the directory that was read in step 1.
Use zip.generate to create the .zip file data, and write it to file using fs.
The resulting file can be downloaded or whatever you would like to do with it. I have seen no issues using this method.
If you want to zip more than one directory, just repeat steps 1 and 2 before you zip.generate, creating a new zip.folder for each directory.
Just use
archive.on("finish",function(){
res.download(__dirname + "/backups/" + zipFile);
})
i am building a nodejs application built using nodejs and express.
the application basically works as a REST URL Calls. front end is written in angularjs.
currently i have to built an application which can play sound and display its text. for simplicity purpose we have extracted the text from the wav file and placed it inside another folder.
In one folder we have a collection of wav files running into thousands and in another folder on same level we have a text files containing all the text
WAV (FOLDER)
TEXT (FOLDER)
Under WAV folder i have a file
2044197581O0140602 - zIgnacio, Ohmar.wav
Under Text Folder i have the same file containing its speect text
2044197581O0140602-zIgnacio,Ohmar.txt
This is exact filename. The problem is that i have to built a system so that all these files can be displayed on the front end . and while playing its text should be shown.(timing is not important here).
I an using nodejs. i know that i cannot upload thousands file from front end. so it has to be done from back end.
can there be a where i can merge both these files into meaningful JSON JS objects and also return the Object URL using nodejs.
Please suggest any good way to handle this architecture using nodejs
I have written this
function FolderReaderMerger(path,pathToMerge,cb)
{
log("Reading File/Folder");
fs.readdir(path, function(err, files1)
{
fs.readdir(pathToMerge, function(err, files2)
{
log(files1);
log(files2);
var obj ={};
obj.wav = (files1);
obj.wavText = (files2);
cb(obj);
});
});
}
but i need to convert wav file conplete path as a URL and add it to JSON. sp that i can hit that url and play that file browser side. any help
TO call above function
FolderReaderMerger(WAV,TEXT,function(res)
{
log("COMBINED FILES");
log(res);
log(res.length);
global.combined = res;
});
And a get URL
app.get("/api/getCombinedFiles",function(req,res)
{
res.send(global.combined);
});
I am able to get the list of files from both folder. But i need to play the audio files on the client side
I had been able to come up with this. i send the file using teh URL sendFile="some file" and then the node checks for that file. if successful i start getting the stream on my client side and i put it directly into video src. But i need morecontrol over this. such as when user click on certain timeline so that i can directly start strweaming from there.
app.get is used to get the location of the folder where i store the files.
used just express and nodejs
function FolderReaderMerger(path,pathToMerge,cb)
{
log("Reading File/Folder To Combine : ");
fs.readdir(path, function(err, audio)
{
fs.readdir(pathToMerge, function(err, audioText)
{
var obj ={};
global.list.audio =audio;
global.list.audioText =audioText;
obj.audio = audio;
obj.audioText = audioText;
cb(obj);
});
});
}
app.get("/audio",function(req,resp)
{
log("App Audio File Serv : ");
var playFile = req.param("playFile");
var filePath = {};
filePath.status =false;
if(playFile!=undefined)
{
log("Params File : "+playFile);
/* log("Requested URL : "+req.url);
log("Total Audio Files : "+global.list.audio.length);*/
var i =0;
while(i!=global.list.audio.length)
{
if(playFile==global.list.audio[i])
{
log("File Found : "+playFile);
//get files location
log(app.get("audioPath")+playFile);
filePath.status = true;
var filePath = app.get("audioPath")+playFile;
log("FILE PATH : "+filePath);
var stat = fs.statSync(filePath);
log(stat);
log(stat.size);
resp.writeHead(200, {
'Content-Type': 'audio/mpeg',
'Content-Length': stat.size
});
var readStream = fs.createReadStream(filePath);
// We replaced all the event handlers with a simple call to readStream.pipe()
log("Streaming.......");
readStream.pipe(resp);
}
else
{
log("Requested Resource Not Found");
}
i+=1;
}
//readStream = fs.createReadStream(app.get("audioPath"));
}
else
{
log("Requested Params Not Found");
resp.send(filePath);
}
});
http.listen(app.get("PORT"),function()
{
consolelog("--------------------------------------------------------");
console.log("Server Started On PORT: "+app.get("PORT"));
console.log("All NPM Initialized");
console.log("Please Wait Checking Connection Status...");
console.log("--------------------------------------------------------");
});
ANy help would be appreciated.