How to get access to directory/subdirectories/subdirectories? - javascript

I have a function that can observe files in directory and subdirectories, but it can't get access to files in the level 3 of subdirectories .
I just need to observe some file changes and modify them so I need to touch all file in the directory recursively
Example: get access to home and home/directories, but can't touch home/sub (sub)directories. How to make that possible?
I want to see all files in the folder
The code I have is:
co(function* () {
let close = yield awatch("./*", (event, filename) => {
//Observing any single changement in file of ext ".html" in local directory
if (cropping_extension(filename) == ".html") {
/**
* Reading the contain of a file and keep it inside a string
*/
console.log(cropping_path(filename));

To have access to all the files in the folder you just need to change ./* to => ./**/*
So in your code you just need to change this part :
let close = yield awatch(" ./**/* ", (event, filename)

How are you hosting the directories? For example, if you're using Express (NodeJS) you'd want to elect a static directory to host all of your assets.

Related

Error when importing .js file in one folder to spec.js file in another folder

I am new to the protractor, and trying to create a project in cucumber using POM. Following is the structure of the project:
In the addCustomerPage.js, I have mentioned the locators as well as the functions to perform a test:
var addCustomerPage = function () {
var BankManagerButton = element(by.buttonText('Bank Manager Login'));
***Other locators*****
this.create = async function(fName,lName,pCode){
await BankManagerButton.click();
****rest of the steps*****
}
}
module.exports = new addCustomerPage();
But when in the spec.js, import the above class, on running the code, it throws the error:
E/launcher - Error: Error: Cannot find module '../pages/addCustomerPage'
Following is the spec.js file's code:
var {
setDefaultTimeout
} = require('cucumber');
const {
expect
} = require('chai');
setDefaultTimeout(10 * 1000);
var addCustomerPage = require('../pages/addCustomerPage');
Given('I open the application and click on create customer button', async function () {
**code*****
});
When('I enter {string}, {string}, {string}', async function (fname, lname, pcode) {
return await addCustomerPage.create(fname, lname, pcode);
});
However, this works fine if the pages folder is under the features folder. Can anyone help on what am I doing wrong here?
../
The symbol above is signalling to go up one file directory.
When the variable is declared like this...
var addCustomerPage = require('../pages/addCustomerPage');
... your computer will go up one folder level from the current directory and search for the pages folder and not find it.
When you copied the pages folder and put it under the feature folder, it can detect it because it falls under the directory that you were searching it for
The solution is to:
Just paste your pages folder under features
or
Modify the file path in the variable to where your pages folder is located
Im guessing you have to go up a directory or two, so use this command ../ to get to where your page folder is
var addCustomerPage = require('../../pages/addCustomerPage');
The idea is to modify the file path to wherever the page folder might be

Using Gulp to build csproj on .less change

I am currently trying to come up with a gulp task that will build the entire .csproj file associated with a particular .less file whenever that .less file changes.
I already have a working task that will do just that, however the restriction I am facing is that the .less file must be in a specific place relative to the .csproj file. If the .less file is one level deeper/higher in the directory, the method I am using to build the .csproj file wont be able to find the correct .csproj file to build.
My current task is based heavily off of one of the tasks found in Kamsar's Habitat repo for Sitecore: https://github.com/kamsar/Habitat
It is as follows:
gulp.task("Auto-Publish-Less",
function() {
var root = "./src";
var roots = [root + "/**/resources/styles", "!" + root + "/**/obj/**/resources/styles"];
var files = "/**/*.less";
gulp.src(roots, { base: root })
.pipe(
foreach(function (stream, rootFolder) {
console.log(rootFolder);
gulp.watch(rootFolder.path + files,
function(event) {
if (event.type === "changed") {
var dest = config.websiteRoot;
console.log("Build project associated with this file: " + event.path);
return gulp.src([event.path + "/../../../*.csproj"]).pipe(publishStream(stream,dest));
}
});
return stream;
}));
});
This works great so long as the .csproj file is 3 levels higher than the .less file. I could also add more wildcards for 2 levels higher, 1 level higher, etc. However, I was looking to see if there was a way in gulp.src to "find" the first matching file, moving up the directory structure, and then stopping once the first match is found. Is there a way to do this in gulp and/or plain-old js?
Check out this package:
Finds the first parent directory that contains a given file or directory:
https://www.npmjs.com/package/find-parent-dir

Gulp - Handle read-only permissions for dest files?

I have image files with read-only attribute set in source folder. I need to copy them to destination folder in most cases several times in gulpfile.js.
I am trying to copy src-to-dest files like this:
gulp.task('copy-images', function () {
gulp.src(path_resource_images + '**/*.jpg')
.pipe(gulp.dest(path_app_images));
});
It works once when the dest folder in empty. But for all next calls I've got an exception that file is read-only in dest folder. How can I remove file attr read-only to make image-copy works every time I call it?
You can use gulp-chmod to handle permissions on your files.
So if you want to set your images readable and writable for everybody, you could go with something like:
var chmod = require('gulp-chmod');
gulp.task('copy-images', function() {
gulp.src(path_resource_images + '**/*.jpg')
.pipe(chmod(666))
.pipe(gulp.dest(path_app_images));
});
By passing options attribute. Set mode value to specify permission for any folders that need to be created as output.
gulp.dest("destination-path-here", {"mode": "0777"})
cheers :-)
rimraf can be used to avoid issues with TFS permissions (by deleting destination files before copying files)
var rimraf = require("rimraf");
gulp.task("images_clean", function (cb) {
rimraf(imagesDest, cb);
});

How to wait until a file is available in a Jake build (Node.js)?

Is there a way in a Node.js Jake build to wait until a certain file has been copied, and advance to do some operation only after the destination file can be found? I think this question pretty much comes down to "is there a way to copy files synchronously in Node.js/Jake?" (Perhaps something else than writing something from scratch, using the combination of fs.readSync and fs.writeSync.)
Background:
I'm developing a web app that is run on Node.js (with Express) during development, but will be deployed on a Java server in production. (We use Jade and Stylus in the client and Express enables us to run the app without generating all the HTML files etc. and deploying it after every change.)
I use Jake for making the build, i.e. generating HTML files from Jade files and CSS from Stylus files etc. Now I'm also trying to concatenate all of the app's JavaScript files into one minimized file and change all the HTML files to use that instead of all the separate JS files that are used in "raw" form during development.
However, I now have a problem with that last step. My idea was to copy all of my Jade files into a temporary directory for the deployment build and replace the reference (in a Jade file used as a header on all HTML pages) to a list of all separate JS files to the one that has just been generated by concatenating and minimizing the whole bunch. But as I first copy all of the Jade files to another location (which happens asynchronously) and try to edit one of the files, opening the file always fails since the copy operation hasn't really finished yet.
This is what I have now (in a simplified form) in my jakefile:
var fs = require('fs');
var fse = require('fs-extra');
var path = require('path');
var glob = require('glob');
var Snockets = require('snockets');
var snockets = new Snockets();
// generating the minimized JS file
snockets.getConcatenation(baseDir + '/scripts/all.js', { minify: true }, function(err, allJs) {
if (err) {
throw err;
}
fs.writeFileSync(generatedJsFileName, allJs);
});
// copying all the Jade files to a temp dir
glob.sync('**/*.*', {
cwd : srcDir
}).forEach(function(file) {
var loadPath = srcDir + '/' + file;
var savePath = targetDir + '/' + file;
fse.mkdirsSync(path.dirname(savePath));
fse.copy(loadPath, savePath);
});
// trying to read one of the copied files (which fails, since the file cannot be found yet)
fs.readFile(targetDir + '/views/includes/head.jade', 'utf8', function(err, data) {
...
});
This might be a stupid question, and a stupid way to try to solve the problem in the first place. So, also suggestions for a better approach are very welcome.
Update:
I also tried using Parseq, putting each operation (creating the JS file, copying the Jade files, reading one file) in its own function, but even that gives me the same error. If I run the script several times without deleting the target directory of the copy operation in between, the file can be found. So e.g. the path is correct and the problem really seems to be about timing.
I didn't really find an answer to the main question so I don't know if this helps anyone else facing the same problem. But I did find a way to get around the problem.
I ended using the same original Jade files for the two different conversions, but in the second conversion I use a custom js function to change the script tag reference to point to the minified file.
I.e.
var data = jade.compile(str, { filename: file, pretty: true })({
css: function(path) {
return '<link rel="stylesheet" href="/styles/' + path + '.css" />';
},
js: function(path) {
var name = '<script src="/scripts/';
if (path == 'all') {
name += generatedJsFileName;
}
else {
name += path + '.js';
}
name += '"></script>';
return name;
}
});
It might not be the prettiest workaround but it works.

In Node.js, reading a directory of .html files and searching for element attributes inside them?

I can't even begin to think about how this would be done. Basically, imagine a folder and it has a static website in it. It has all the images, styles and html files etc. With my Node application, I want to look inside this folder, get just the .html files only and then pick just the .html files that have the attribute 'data-template="home"' inside them.
I know this seems a little odd maybe, but it's for a project that requires the user to upload their static website files and then my Node app does things to them files.
Anyhow, was just curious about iterating over certain filetypes and then looking inside them... Any help with approaching this would really help me.
Many thanks, James
This piece of code will scan for all files in a directory, then read the contents of .html files and then look for a string data-template="home" in them.
var fs = require('fs');
fs.readdir('/path/to/html/files', function(err, files) {
files
.filter(function(file) { return file.substr(-5) === '.html'; })
.forEach(function(file) { fs.readFile(file, 'utf-8', function(err, contents) { inspectFile(contents); }); });
});
function inspectFile(contents) {
if (contents.indexOf('data-template="home"') != -1) {
// do something
}
}
If you need more flexibility, you could also use the cheerio module to look for an element in the html file with that attribute:
var cheerio = require('cheerio');
function inspectFile(contents) {
var $ = cheerio.load(contents);
if ($('html[data-template="home"]').length) {
// do something
}
}
Take a look at the nodejs filesystem module
http://nodejs.org/docs/v0.5.3/api/fs.html
You could use fs.readdir() to get the names of all the files, then read the .html ones to find 'data-template=home'.

Categories