Get all files with specified extension node.js - node.js

I am using node.js. I want to loop through all files with extension .coffee,
but I have nowhere found an example.

Following function will return all the files in the specified directory with the regex provided.
Function
var path = require('path'), fs=require('fs');
function fromDir(startPath,filter,callback){
//console.log('Starting from dir '+startPath+'/');
if (!fs.existsSync(startPath)){
console.log("no dir ",startPath);
return;
}
var files=fs.readdirSync(startPath);
for(var i=0;i<files.length;i++){
var filename=path.join(startPath,files[i]);
var stat = fs.lstatSync(filename);
if (stat.isDirectory()){
fromDir(filename,filter,callback); //recurse
}
else if (filter.test(filename)) callback(filename);
};
};
Usage
fromDir('../LiteScript',/\.coffee$/,function(filename){
console.log('-- found: ',filename);
});

Related

How do you get a list of the names of all files present in a web server directory using Node.js?

when using fs.readdir it gives me file name present in the given path but how can get file name stored on a specific path on a web server.
I believe you are using this function
fs.readdir ('../', function (err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
});
To access the
root(or C drive) use / .
current directory use ./.
parent directory use ../.
parent of parent directory use ../../.
To access a directory in the parent directory use ../sibling_name.
Now I believe you can navigate through directories. Navigate through directories and list the files and the folders contained in the directory.
I think it will help u.
const fs = require('fs');
const path = require('path');
function getFile(dirPath) {
const files = fs.readdirSync(dirPath);
files.forEach(function (item) {
const currentPath = path.join(dirPath, item),
isFile = fs.statSync(currentPath).isFile(),
isDir = fs.statSync(currentPath).isDirectory();
if (isFile) {
// console.log(currentPath);
} else if (isDir) {
console.log(currentPath);
getFile(currentPath);
}
});
}
getFile('./'); // this is your server path

Creating and naming a new file according to a string - gulp

Total newbie in Gulp, really would like some assistance..
I am trying to name & create a new file using a string that exist in another file. this will give me the name of the white label that was deployed onto the server.
The content of the file that holds the string is (among other things) {"TITLE":"name_env"}
name_env should be the new name of the file with the suffix of .web
meaning that the new file would be like this name_env.web
What I've came up until now was:
gulp.task('label', function () {
var str = require('path/to/file/file.json')
return file('label', str, {src: true})
.pipe(gulp.dest('build/'))
});
Am I on the right track ?
Hopefully I've managed to explain myself..
Here's gulp file which will do your task(assuming there's dist folder already exist!!)
var gulp = require('gulp');
var fs = require('fs');
gulp.task('label', function() {
var buffer = JSON.parse(fs.readFileSync('path/to/file.json', 'utf8'));
return fs.writeFile('dist/' + buffer['TITLE'] + '.web' , buffer, { flag: 'wx' }, function(err) {
if (err) throw err;
console.log("It's saved!");
});
});

Node.js moving contents of subdirectory into current directory

I have a Node script that downloads a zip into tmp/archive.zip and extracts that to tmp/archive.
I would like to move the contents of tmp/archive into .. I'm having difficulty finding how to use fs.rename in a way that is equivalent to mv tmp/archive/* .
I have tried fs.rename('tmp/archive/*', '.', function(err){ but that gives me the following error: Error: ENOENT: no such file or directory, rename 'tmp/archive/*' -> '.'
I have also tried using glob to list the contents of tmp/archive and then iterate through it and move the files using fs-extra's move, as follows:
glob('tmp/archive/*', {}, function(err, files){
for (var i = files.length - 1; i >= 0; i--) {
fs.move(files[i], '.', function(err){});
}
}.bind(this));
which results in the folowing error: Error: EEXIST: file already exists, link 'tmp/archive/subdirectory' -> '.'
I could just call mv tmp/archive/* . from the script but i would like to avoid that if possible. Is there something obvious I am missing? How can I go about doing this?
Here's one way to move a directory of files from one location to another (assuming they are on the same volume and thus can be renamed rather than copied):
var Promise = require('bluebird');
var fs = Promise.promisifyAll(require('fs'));
var path = require('path');
function moveFiles(srcDir, destDir) {
return fs.readdirAsync(srcDir).map(function(file) {
var destFile = path.join(destDir, file);
console.log(destFile);
return fs.renameAsync(path.join(srcDir, file), destFile).then(function() {
return destFile;
});
});
}
// sample usage:
moveFiles(path.join(".", "tempSource"), path.join(".", "tempDest")).then(function(files) {
// all done here
}).catch(function(err) {
// error here
});
This will move both files and sub-directories in the srcDir to destDir. Since fs.rename() will move a sub-directory all at once, you don't have to traverse recursively.
When designing a function like this, you have a choice of error behavior. The above implementation aborts upon the first error. You could change the implementation to move all files possible and then just return a list of files that could not be moved.
Here's a version that renames all files that it can and if there were any errors, it rejects at the end with a list of the files that failed and their error objects:
function moveFilesAll(srcDir, destDir) {
return fs.readdirAsync(srcDir).map(function(file) {
var destFile = path.join(destDir, file);
var srcFile = path.join(srcDir, file);
return fs.renameAsync(srcFile, destFile).then(function() {
return {file: srcFile, err: 0};
}).catch(function(err) {
console.log("error on " + srcFile);
return {file: srcFile, err: err}
});
}).then(function(files) {
var errors = files.filter(function(item) {
return item.err !== 0;
});
if (errors.length > 0) {
// reject with a list of error files and their corresponding errors
throw errors;
}
// for success, return list of all files moved
return files.filter(function(item) {
return item.file;
});
});
}
// sample usage:
moveFilesAll(path.join(".", "tempSource"), path.join(".", "tempDest")).then(function(files) {
// all done here
}).catch(function(errors) {
// list of errors here
});

Nodejs illegal operation on a directory

Im trying to compile a folder of markdown files into a single PDF with markdown-pdf NPM package.
I have a simple script to do the job:
var mpdf = require('markdown-pdf');
var fs = require('fs');
var mDocs = fs.readdirSync('./understandinges6/manuscript/');
mDocs = mDocs.map(function(d) { return 'understandinges6/manuscript/' + d });
var Book = 'understandinges6.pdf';
mpdf().concat.from(mDocs).to(Book, function() {
console.log("Created", Book);
});
But when i execute the script, this error appears:
events.js:154
throw er; // Unhandled 'error' event
^
Error: EISDIR: illegal operation on a directory, read
at Error (native)
It's weird because i'm in my home folder with the respective permissions. I'm specifying the output folder/file in the script and just reading with fs.readdirSync.
Any idea about this?
mDocs = mDocs.map(function(d) { return 'understandinges6/manuscript/' + d }); you forgot to add "./". Rewrite to mDocs = mDocs.map(function(d) { return './understandinges6/manuscript/' + d });
Cool, i get the problem here:
In the manuscripts/ folder are a images/ sub-folder with some png's. When the scripts tryed to read and transform images/ from .md to .pdf the error was fired.
Here is the array with the images/ inside:
[ 'understandinges6/manuscript/00-Introduction.md',
'understandinges6/manuscript/01-Block-Bindings.md',
'understandinges6/manuscript/02-Strings-and-Regular-Expressions.md',
'understandinges6/manuscript/03-Functions.md',
'understandinges6/manuscript/04-Objects.md',
'understandinges6/manuscript/05-Destructuring.md',
'understandinges6/manuscript/06-Symbols.md',
'understandinges6/manuscript/07-Sets-And-Maps.md',
'understandinges6/manuscript/08-Iterators-And-Generators.md',
'understandinges6/manuscript/09-Classes.md',
'understandinges6/manuscript/10-Arrays.md',
'understandinges6/manuscript/11-Promises.md',
'understandinges6/manuscript/12-Proxies-and-Reflection.md',
'understandinges6/manuscript/13-Modules.md',
'understandinges6/manuscript/A-Other-Changes.md',
'understandinges6/manuscript/B-ECMAScript-7.md',
'understandinges6/manuscript/Book.txt',
'understandinges6/manuscript/images' ]
Solution? Just pop() the mDocs array (now just docs):
var mpdf = require('markdown-pdf');
var fs = require('fs');
var mDocs = fs.readdirSync('understandinges6/manuscript/');
var docs = mDocs.map(function(d) { return 'understandinges6/manuscript/' + d });
docs.pop();
var Book = 'understandinges6.pdf';
mpdf().concat.from(docs).to(Book, function() {
console.log("Created", Book);
});

NodeJS Reading all files in a dir by each line

I am fairly new to NodeJS, I am trying to read all files in a given dir and then print out the results line by line using the code below
var fs=require('fs'),fsf = require('fs'),lazy = require('lazy');
var fr;
var dir = '/path/to/dir';
fs.readdir(dir,function(err,files){
if (err) throw err;
files.forEach(function(file){
console.log(file);
fr = fsf.createReadStream(file);
//console.log(fr);
new lazy(fr).lines.forEach(function(line){
console.log(line.toString());
});
});
I am getting the following error
Cannot call method 'toString' of undefined
Any pointers will be really appreciated!
Update: - There were actually two issues
(main) The blank lines in the individual files were causing this
exception.
The hidden files were getting picked up by the program.
Corrected both and here is the refactored code
var fs=require('fs'),lazy = require('lazy');
var fr;
var dir = '/path/to/dir';
fs.readdir(dir,function(err,files){ //Get a listing of all the files in the dir
if (err) throw err;
files.forEach(function(file){
if(file.search('\\.md') != -1) { //Only read markdown files
console.log(file);
fr = fs.createReadStream(file);
new lazy(fr).lines.forEach(function(line){
if (typeof line != 'undefined'){ // Skip blank lines within the files
if ((line.toString().search('\\+') != -1)||(line.toString().search('#') != -1)){
console.log(line.toString());
}
}
});
}
});
});
The code seems fine and is working with other directories and on other machines. After some investigation it seems to be an issue with the .DS_Store hidden files in the directory. I was trying this on a Mac with OSX 10.9.4. I am not 100% sure, but for now that seems to be the likely cause of the error.
Thanks!

Resources