Create Structured Data - javascript

lets assume i have this (snippet):
var filesarray = [];
if(req.files){
req.files.forEach(function(file){
var fileName = file.filename;
var filePath = file.path;
filesarray.push(
filePath
);
})
}
And later i push it with mongoose:
DB.create({
filepaths: filesarray,
}), function (err, res) {
if (err) {
throw err;
}else{
console.log("1 document inserted");
DB.close()
}}
});
The result i receive is not really what i want, because in mongodb i get a comma separated list, like:
filepaths
/files/1540474914824.png,/files/1540474914828.png,files/1540474914831.png
I would like to have something like:
filepaths
filename -> filepath
filename -> filepath
filename -> filepath
i hope i could make clear whats the goal. I am sure there is a elegant way to reacht the goal, so could someone please give me a direction.
Thanks,
Regards

First off you cant have more than one key in am object so {filepaths: {file: '1', file: '2'}} will not work. You will need to have a unique name per file/path
var files = {};
if(req.files){
req.files.forEach(function(file){
var fileName = file.filename;
var filePath = file.path;
files[fileName] = filePath;
})
}
you could use map to have an array of object but this seems more cumbersome to me
var files;
if(req.files){
files = req.files.map(function(file){
var fileName = file.filename;
var filePath = file.path;
return { [fileName]: filePath };
})
}

Related

Save js variable data in txt

I have the following code and I need to save allProducts in a .txt file with json format. How can I achieve that?
var fruit = [{"name: x","id: y",..}, {...},...]
var driedFruitsNut = [{"name: x","id: y",..}, {...},...]
fruit.forEach((item) =>{
item.category = "Fruits & Vegetables";
item.subtCategory = "Fruit";
});
driedFruitsNut.forEach((item) => {
item.category = "Fruits & Vegetables";
item.subtCategory = "Dried Fruits & Nuts";
});
var allProducts = fruit.concat(driedFruitsNut);
I tried something like this; but I have no idea if this is even a correct code:
var fs = require('fs');
fs.writeFile("test.txt", allProducts, function(err) {
if (err) {
console.log(err);
}
});
but when I run node fetchFruitVeg.js in my terminal. I get a text file looking like this:
You can try something like this:
var fs = require('fs');
fs.writeFile("test.txt", JSON.stringify(allProducts), function(err) {
if (err) {
console.log(err);
}
});
since allProducts is a javascript object, first you need to convert it into normal string data to write it in a .txt file or .json file

I want to rename a particular string in multiple filenames in nodejs

I want to rename a particular string in filenames. I am using glob and path to extract multiple file names from multiple locations. Now I just want to rename those files like abcd-change-name.js to abcd-name-changed.js
Here's what I have done so far
var glob = require("glob")
var path = require('path')
const fs = require('fs')
glob(process.cwd() + "/directory/**/*-change-name*.js", {}, function (er,
files) {
for(i=0; i<files.length; i++){
var f = path.basename(files[i])
var d = path.dirname(files[i])
fs.renameSync(files[i] , d + '/name-changed.js', function (err) {
if (err) throw err;
console.log('renamed complete');
});
}
})
The code is changing all the files with the js extension to name-changed.js in their respective folders.
Your code uses has the line fs.renameSync(files[i], d + '/name-changed.js', ... but this line of code renames files[i] to '[foldername]/name-changed.js'.
I would suggest having something like fs.renameSync(files[i], files[i].replace('change-name', 'name-changed'), ...
In other words, you have told fs to rename the file to have a filename of 'name-changed.js' but you want it to contain the original filename data but with 'change-name' replaced with 'name-changed'.
Here is a full code example based on your code.
var glob = require("glob")
var path = require('path')
const fs = require('fs')
glob(process.cwd() + "/directory/**/*-change-name*.js", {}, function (er,
files) {
for(i=0; i<files.length; i++){
var f = path.basename(files[i])
var d = path.dirname(files[i])
fs.renameSync(files[i] , files[i].replace('change-name', 'name-changed'), function (err) {
if (err) throw err;
console.log('renamed complete');
});
}
})

get file name of selected file

How can I get only the name of the selected Data. I do the following but get the whole path of the File. I would like to display the filename for the user
var dialog = require('electron').remote.dialog;
var url;
document.getElementById('openButton').onclick = () => {
dialog.showOpenDialog((fileName) => {
if(fileName === undefined) {
alert('No file selected');
} else {
console.log(fileName)
url = fileName[0];
console.log(url);
$('#dataFileName').html(url)
}
})
};
What i get is "/Users/void/Desktop/abc.xlsx" and I would like to have in addition to that only the file i opened.
You can also use path.basename()
const {basename} = require('path')
let filePath = "/Users/void/Desktop/abc.xlsx"
let fileName = basename(filePath)
Here is a simple way you can grab just the file name:
var filePath = "/Users/void/Desktop/abc.xlsx";
var fileName = filePath.replace(/^.*[\\\/]/, '');
console.log(fileName);
Here is a fiddle to demonstrate.
If I understood correctly, you can use this:
var mystring = "/Users/void/Desktop/abc.xlsx"; //replace your string
var temp = mystring.split("/"); // split url into array
var fileName = temp[temp.length-1]; // get the last element of the array
What you basically do is to split your url with "/" regex, so you get each bit, and filename is always the last bit so you can get it with array's length you just created.

nodejs: compare function generated JSON data to JSON file

I have a function that scans a directory and creates a JSON file with the audio files metadata. I want it to check if the file already exists and only overwrite if there is any diference between the file that was created from the last time the script was run and the data from the the second time it runs.
This is my code:
var fs = require('fs');
var nodeID3 = require('node-id3');
var path = require('path');
var tracksPath = './public/tracks/';
var dataPath = './public/data/';
fs.readdir(tracksPath,function(err,files){
if(err) {
throw err;
}
//Read the tracks metadata
var tracksMetadata = [];
files.forEach(function(trackName){
var trackFile = nodeID3.read(tracksPath + trackName);
//If the track returns metadata push it to the array
if (trackFile.title && trackFile.artist){
var metadata = {
"filename" : trackName,
"title" : trackFile.title,
"artist" : trackFile.artist
};
tracksMetadata.push(metadata);
}
//If no metadata is found ignore and log it to the console
else if (trackName.charAt(0) != "."){
var filename = {
"filename" : trackName
};
tracksMetadata.push(filename);
console.log(trackName + " doesn't have metadata. Ignoring.");
}
if(fs.existsSync(dataPath + "metadata.json")){
fs.readFile(dataPath + "metadata.json",'utf8', function (err, data){
if (err) throw err;
console.log(JSON.parse(JSON.stringify(data)));
console.log(JSON.parse(JSON.stringify(tracksMetadata)));
console.log(Boolean(JSON.parse(JSON.stringify(data)) == JSON.parse(JSON.stringify(tracksMetadata))));
});
}
});
fs.writeFile(path.join(dataPath, 'metadata.json'),
JSON.stringify(tracksMetadata),'utf8', function(err){
if(err){
throw err;
}
console.log("Tracks Metadata JSON created succesfully");
});
});
Right now I'm only writing to the console a Boolean value that checks wether the data from the file and the data generated by the function are equal and so far I get false.
What should I do?

Node.js Asynchronous read and write

I am having problem with asynchronous file read and write operations. only the last file is written to the server.
js:
function uploadassignment(req, res){
var path;
var multiparty = require("multiparty");
var form = new multiparty.Form();
console.log(req.query);
var filelength = req.query.filecount;
console.log(filelength);
form.parse(req, function(err, fields, files){
console.log(req.body);
for(i=0;i<filelength;i++){
var img = files.file[i];
console.log(img);
console.log('divide');
var fs = require('fs');
fs.readFile(img.path, function(err, data){
var originalfile = img.originalFilename.split('.');
console.log(originalfile);
var file_ext = originalfile[1];
path = "public/assignments/"+img.originalFilename;
console.log(path);
fs.writeFile(path, data, function(error){
if(error)console.log(error);
});
})
}
});
};
This is a common bug caused by using a loop variable without a closure. By the time the callback for the read operation is invoked, the loop has terminated and the index i points to the last element (and hence your img contains the last file). Create a function (a closure) that accepts the index as the parameter and call this function from the loop:
function blah(i) {
var img = files.file[i];
console.log(img);
console.log('divide');
var fs = require('fs');
fs.readFile(img.path, function(err, data){
var originalfile = img.originalFilename.split('.');
console.log(originalfile);
var file_ext = originalfile[1];
path = "public/assignments/"+img.originalFilename;
console.log(path);
fs.writeFile(path, data, function(error){
if(error)console.log(error);
});
})
}
for(i=0;i<filelength;i++) blah(i);
This isn't quite an answer, but it is too long for a comment.
What is not working? The file reading/writing bit of your code works fine:
var fs = require("fs")
img = {
path: "./test.txt",
originalFilename: "test.txt"
}
fs.readFile(img.path, function(err, data){
if(err)console.log(err);
var originalfile = img.originalFilename.split('.');
console.log(originalfile);
var file_ext = originalfile[1];
path = "public/assignments/"+img.originalFilename;
console.log(path);
fs.writeFile(path, data, function(error){
if(error)console.log(error);
});
})
With a directory structure like:
script.js
text.txt
public
assignments
I think your problem might be that you are assigning "fs" locally, then trying to call it from an async function. That might be why only the last one works (maybe.)
Try moving var fs = require('fs'); to the top of your code.

Categories

Resources