I am trying to move files from one directory to another using the mv module. The problem is, once the files are moved, the source directory gets deleted. I dont want this, I want only the files that are moved to be deleted from the source directory. The source directory should remain (even if it is empty). Not sure how to do this with the mv module (or if there are any other options).
My code
var pathToPdf = path.join(__dirname, '../pathToPdf/');
` var intermediate = path.join(__dirname, '../intermediate/');
fs.readdir(pathToPdf, function(err, files) {
if (err) return;
files.forEach(function(file){
mv(pathToPdf, intermediate, function(err) {
if(err){
console.log("oops!")
}
});
----move code ---
This code is moving the files to intermediate directory, but the pathToPdf directory gets deleted, which I want to avoid. Please advise.
files.forEach(function(file){
console.log(file)
console.log("pathToPdf", pathToPdf+file)
mv(pathToPdf+file, intermediate+file, function(err) {
if(err){
console.log("oops!")
}
});
Related
I need to list the files contained in different folders (all these folders are in the same directory). So what I thought to do was this:
fs.readdir(unzippedPath, (err, folders) => {
folders.forEach((folder) => {
console.log(`${unzippedPath}/${folder}/`); // all good till here
fs.readdir(`${unzippedPath}/${folder}}/`, (err, files) => {
console.log('files: ', files);
});
});
});
First read all the folders inside the main directory (unzippedPath) then for each of those folders read the files in them.
While the first log print what the directory of the right folder, the second log returns undefined.
While the direcoty logged is correct, I do not understand why it doesn't log the files for each folder.
You just have a typo. You have one } more in the first parameter of the nested fs.readdir.
${unzippedPath}/${folder}}/ should be ${unzippedPath}/${folder}/.
I need to delete only the json files within a directory (multiple levels). I'd hazard a guess that it's possible with fs-unlinkSync(path)
But I can't find a solution without specifying the individual file name.
I was hoping to solve it with the following...
fs.unlinkSync('./desktop/directory/*.json')
but unfortunately the asterisk wouldn't select all. Any suggestion please?
You can list files using fs.readdirSync, then call fs.unlinkSync to delete. This can be called recursively to traverse an entire tree.
const fs = require("fs");
const path = require("path");
function deleteRecursively(dir, pattern) {
let files = fs.readdirSync(dir).map(file => path.join(dir, file));
for(let file of files) {
const stat = fs.statSync(file);
if (stat.isDirectory()) {
deleteRecursively(file, pattern);
} else {
if (pattern.test(file)) {
console.log(`Deleting file: ${file}...`);
// Uncomment the next line once you're happy with the files being logged!
try {
//fs.unlinkSync(file);
} catch (err) {
console.error(`An error occurred deleting file ${file}: ${err.message}`);
}
}
}
}
}
deleteRecursively('./some_dir', /\.json$/);
I've actually left the line that deletes the file commented out.. I'd suggest you run the script and be happy the files that are logged are the right ones. Then just uncomment the fs.unlinkSync line to delete the files.
I'm having trouble identifying the path to a file in the public directory c:\TEMP\todos\.meteor\local\build\programs\server\public\main.py. Meteor complains the file or directory doesn't exist. Already searched the other postings about the similar issue (e.g., Reading files from a directory inside a meteor app) but didn't help.
Here is the error message.
=> Your application has errors. Waiting for file change.
=> Modified -- restarting.
=> Meteor server restarted
W20151206-04:05:57.893(-5)? (STDERR) Error inside the Async.runSync: ENOENT, no such file or directory 'c:\TEMP\todos\.meteor\local\build\programs\server\public'
Client code
Meteor.call('runPython', function(err, response) {
if(err){
} else {
console.log(response);
}
})
Server code
Meteor.startup( function (){
Meteor.methods({
runPython: function (){
var PythonShell = Meteor.npmRequire('python-shell');
var fs = Meteor.npmRequire('fs');
var runPython = Async.runSync(function (done){
var files = fs.readdirSync('./public/');
// PythonShell.run('main.py', function ... was tried first but Meteor complained that "main.py doesn't exist". So below is a different attempt.
var py = _(files).reject(function(fileName){
return fileName.indexOf('.py') <0;
})
PythonShell.run(py, function (err) {
// PythonShell.run(path.join(py,"main.py") ... was also tried but resulted in the same error
if (err) throw err;
console.log('script running failed');
});
})
return "Success";
}
})
})
All files inside the public folder should be read using '/':
var files = fs.readdirSync('/');
More here: http://docs.meteor.com/#/full/structuringyourapp
For server-side only (might be your case and probably a better solution) you can put everything under the private/ folder and access them by using the Assets API: http://docs.meteor.com/#/full/assets_getText
Clearly I was overthinking it. Specifying a full path to the file was all I needed to do.
PythonShell.run('c:\\project\\public\\main.py', function ...
If your application allows moving the Python script to /private instead of /public, you can take advantage of Meteor's Assets:
Assets allows server code in a Meteor application to access static server assets, which are located in the private subdirectory of an application’s tree. Assets are not processed as source files and are copied directly into your application’s bundle.
e.g. If you move your script to /private/scripts/script.py you can generate the absolute path the Meteor way by doing Assets.absoluteFilePath('scripts/script.py').
On Windows 7. In a proprietary app that contains chromium browser. Running on Node.js and Express. In my file 'javascripts/getMyFiles.js' I'm trying to use the following code from: http://nodeexamples.com/2012/09/28/getting-a-directory-listing-using-the-fs-module-in-node-js/
#!/usr/bin/env node
var fs = require("fs"),
path = require("path");
var p = "../"
fs.readdir(p, function (err, files) {
if (err) {
throw err;
}
files.map(function (file) {
return path.join(p, file);
}).filter(function (file) {
return fs.statSync(file).isFile();
}).forEach(function (file) {
console.log("%s (%s)", file, path.extname(file));
});
});
I have 3 problems with this code:
I get and 'Unexpected token ILLEGAL' error from the '#!/use/bin/end node' line
After deleting that first line of code I get the error 'Uncaught ReferenceError: require is not defined'. If I move the '...require...' lines to my root app.js file then the object fs is undefined in my getMyFiles.js file.
I need to specify which folder to list when my app gets an event
I get that require is not available on the client-side, but I don't want to get a list of files from the client side. The files I want to list are in the same path as all of my other files, '/public/Docs'. I can load a known file straight away, but I need to present the user with a list of available documents first. Any assistance will be most appreciated.
Here is my code:
exports.post_handler = function(req, res) {
var photo = req.files.image;
console.log(photo);
console.log(__dirname);
fs.readFile(photo.path, function(err, data) { //I use the path module to join the image path strings
fs.rename(path.join(__dirname, "public/temp"), path.join(__dirname,"public/images"), function(err) {
if (err) {
console.log(err);
res.redirect("/");
}
else {
console.log("file " + photo.name + "written to uploads folder");
res.redirect("/home");
}
});
});
}
I'm trying to move an uploaded image file from my temp folder to my uploads folder. I'm using the fs module to do this. After granting full permissions to both files to all users on my PC, I'm getting the following error:
{ [Error: EPERM, rename 'dir\public\temp']
errno: 50,
code: 'EPERM',
path: 'dir\\public\\temp' }
I'm not sure what's going wrong here. Anyone have any ideas?
What your code is trying to do is rename the public/temp directory to public/images. public/images presumably already exists, so you're getting that error. In other words, nowhere in there are you moving the image, you're instead 'moving' (renaming) the directory public/temp to public/images.
You have to use photo.path instead. Use it as the first parameter and then perhaps the second parameter should path.join images directory to path.basename(photos.path).