I am using faker.js
https://www.npmjs.com/package/faker
to generate random data. It works fine although when I try to create a path like this
faker.system.directoryPath() + '/' + faker.system.filePath()
I have always got undefined in both, so it seems that it exists but doesn't return anything.
Did anyone use one of these methods before?
Thanks in advance, any help would be really appreciated.
Bye
Those functionalities are not implemented - take a look into https://github.com/Marak/faker.js/blob/master/lib/system.js#L132 and https://github.com/Marak/faker.js/blob/master/lib/system.js#L141
/**
* not yet implemented
*
* #method faker.system.filePath
*/
this.filePath = function () {
// TODO
};
Some proof of concept how it can be implemented:
var faker = require('faker');
var path = require('path');
faker.directoryPath = function() {
return path.format({base: faker.fake("{{random.words}}").replace(/ /g, path.sep).toLowerCase()})
}
console.log(faker.directoryPath() + path.sep + faker.system.fileName()) // e.g. avon\re-engineered\strategist_gorgeous_wooden_fish_cambridgeshire.sm
Related
I'm in another pickle I've realized over the past week that my images are not loading due to the fact the links have expired so I wanna find out how to go about using a file directory in the code.
Here's what I've tried:
});
client.on('message', message => {
if (message.content.startsWith('L!hug')) {
var fs = require('fs');
var files = fs.readdirSync('C:\Users\nevbw\Desktop\games\FBIBot\images\hugs')
/* now files is an Array of the name of the files in the folder and you can pick a random name inside of that array */
let chosenFile = files[Math.floor(Math.random() * files.length)]
}
});
and
});
client.on('message', message => {
if (message.content.startsWith('L!hug')) {
const path = 'C:\Users\nevbw\Desktop\games\FBIBot\images\hugs';
const fs = require('fs');
fs.readdirSync(path).forEach(file => {
ranfile = Math.floor(Math.random() * file.length);
message.channel.sendFile(ranfile);
})
}
});
found out through searching and searching but found a answer the modified it to this, i hope people use this in future reference!
const num = (Math.floor(Math.random()* 5)+1).toString(); message.channel.send({files: [`./slap/slap${num}.gif`]})
Using fs.readdirSync('./images/') instead of fs.readFileSync('./images/') works easier, but then you will have to create the folder inside of VSC and put the images in the folder, you can also drag and drop the images into the solution and use:
var files = fs.readdirSync(`./images/`).filter(file => file.endsWith('.png'))
so that when it looks for an image, it doesn't select anything else. hope it helps for some people.
Happy to help.
You're using FS the wrong way. This Is What It Should Look Like :D Also Here Is Some Documentation on It ( https://nodejs.org/dist/latest-v13.x/docs/api/fs.html ).
-- Code --
Also Just As A Tip! I See You Are Using Full Directories, That's Quite Innificeng (E.g if You Change Your Username, Drive ID, etc.) so in fs provided the image is in the same folder you can just do ./(ImageName), or if it is in the same folder but under another say /FBIBot/Images you can do ./Images/(ImageName). ^^
--
What The Error Was: (I Unfortunately Cannot Test it But I Am Like 99% Sure).
You Were Using fs.readdirSync(path).forEach(file => { When You Were Meant To Be Using fs.readfilesync(path).forEach(file => {.
-- First Code --
});
client.on('message', message => {
if (message.content.startsWith('L!hug')) {
var fs = require('fs');
var files = fs.readfileSync('C:\Users\nevbw\Desktop\games\FBIBot\images\hugs')
/* now files is an Array of the name of the files in the folder and you can pick a random name inside of that array */
let chosenFile = files[Math.floor(Math.random() * files.length)]
}
});
-- Second Code --
});
client.on('message', message => {
if (message.content.startsWith('L!hug')) {
var fs = require('fs');
var files = fs.readFileSync('C:\Users\nevbw\Desktop\games\FBIBot\images\hugs')
/* now files is an Array of the name of the files in the folder and you can pick a random name inside of that array */
let chosenFile = files[Math.floor(Math.random() * files.length)]
}
});
^^
I'd like for my jest snapshots to be created as a sibling to my test file
I current have my snapshots being put in the default __snapshots__ folder.
Current:
What I would like to achieve:
I found this post on github: https://github.com/facebook/jest/issues/1650
In the thread someone says the following should work but I haven't had any luck (even with changing the regex and other changes):
module.exports = {
testPathForConsistencyCheck: 'some/example.test.js',
resolveSnapshotPath: (testPath, snapshotExtension) =>
testPath.replace(/\.test\.([tj]sx?)/, `${snapshotExtension}.$1`),
resolveTestPath: (snapshotFilePath, snapshotExtension) =>
snapshotFilePath.replace(snapshotExtension, '.test'),
}
In package.json (or if you use jest.config.js) you need to add the path for the snapshotResolver file:
"jest": {
"snapshotResolver": "./snapshotResolver.js"
}
snapshotResolver.js is a file with code that you found in a Github issue.
In my case this file was located at the root of the project (near node_modules folder)
These solutions are more complicated that is needed for what you are trying to do.
As per pointed out in https://github.com/facebook/jest/issues/1650
Solution
Create a file: I used - 'jest/snapshotResolver.js'
module.exports = {
resolveSnapshotPath: (testPath, snapshotExtension) =>
testPath + snapshotExtension,
resolveTestPath: (snapshotFilePath, snapshotExtension) =>
snapshotFilePath.replace(snapshotExtension, ''),
testPathForConsistencyCheck: 'some.test.js',
};
in your jest config set that file to the resolver
snapshotResolver: './jest/snapshotResolve.js',
or if your jest config in package.json:
"snapshotResolver": "./jest/snapshotResolve.js",
Explanation
In short these two functions mirror each other, one takes the test file path and returns the snapshot path, the other takes the snapshot path and returns the test file path. The third is a file path example for validation.
Clearer code To help clarify what is going on
One thing to keep in mind is that the path is the full path not the relative path.
/**
*
* #param testPath Path of the test file being test3ed
* #param snapshotExtension The extension for snapshots (.snap usually)
*/
const resolveSnapshotPath = (testPath, snapshotExtension) => {
const snapshotFilePath = testPath + snapshotExtension; //(i.e. some.test.js + '.snap')
return snapshotFilePath;
}
/**
*
* #param snapshotFilePath The filename of the snapshot (i.e. some.test.js.snap)
* #param snapshotExtension The extension for snapshots (.snap)
*/
const resolveTestPath = (snapshotFilePath, snapshotExtension) => {
const testPath = snapshotFilePath.replace(snapshotExtension, '').replace('__snapshots__/', ''); //Remove the .snap
return testPath;
}
/* Used to validate resolveTestPath(resolveSnapshotPath( {this} )) */
const testPathForConsistencyCheck = 'some.test.js';
module.exports = {
resolveSnapshotPath, resolveTestPath, testPathForConsistencyCheck
};
Also, in addition to the path to the snapshotResolver as suggested in the Vasyl Nahuliak's answer, to achieve having the snapshot and the test files looking like this:
file.test.js
file.test.js.snap
your snapshotResolver should look like this:
module.exports = {
testPathForConsistencyCheck: 'some/example.test.js',
resolveSnapshotPath: (testPath, snapshotExtension) =>
testPath.replace(/\.test\.([tj]sx?)/, `.test.$1${snapshotExtension}`),
resolveTestPath: (snapshotFilePath, snapshotExtension) =>
snapshotFilePath.replace(snapshotExtension, ''),
};
I am quite new to Node and gulp which I am trying to learn.
As an experiment, I am trying to write a little gulp task that just prints on the console the content of the streams it receives from the gulp.src() method. So, I have implemented it this way (the commented code works and the not commented code does not work). What am I doing wrong?
var gulp = require('gulp');
var through = require('through2');
var connect = require('gulp-connect');
var fs = require('fs');
var PATHS = {
src : 'src/**/*.ts',
html : 'src/**/*.html',
css : 'src/**/*.css'
};
gulp.task('test', function() {
// This is working !!!
/*
* fs.createReadStream('ex.txt').pipe(through(function(chunk, enc, callback) {
* console.log("Text is: " + chunk.toString());
*
* this.push(chunk)
*
* callback() })).pipe(fs.createWriteStream('out.txt')).on('finish',
* function() { console.log("Working"); })
*/
// But this is not working, why !!!
var writable = through.obj(function(chunk, enc, callback) {
if (chunk.isStream()) {
console.log("Chunk is stream ");
console.log("Path is: " + chunk.path);
} else if (chunk.isBuffer()) {
console.log("Chunk is buffer ");
} else {
console.log("Chunk is something else then stream or buffer");
}
this.push(chunk);
callback();
});
gulp.src('ex.txt').pipe(writable);
});
BTW - How can I tell what kind of object is 'chunk' and what methods I have available to call on that object (where are they documented – I am used to Java style documentation)?
These might be trivial questions for experienced Node.js and gulp users but I am having trouble to understand them.
If anybody can help me to get through this learning curve I would greatly appreciate it.
I set out to make my first node module. It's very simple, it just takes the input from a user and validates if it is valid or not by comparing it to a large data file. The data file is just a json object. Here is the code for index.js
// borrowed heavily from http://quickleft.com/blog/creating-and-publishing-a-node-js-module
/**
* Valiate a NAICS codes using 2012 NAICS codes
*
* #param {String} 2 to 6 digit numeric
* #return {Boolean}
*/
var fs = require('fs');
var obj = JSON.parse(fs.readFileSync('codes.json', 'utf8'));
module.exports = {
validateNAICS: function(inNAICS) {
inNAICS = inNAICS || "";
if (inNAICS.length > 6) { return false };
if (inNAICS.length < 2) { return false };
if (obj.hasOwnProperty(inNAICS)) { return true };
return false;
},
/**
* Given a NAICS code return the industry name
*
* #param {String} 2 to 6 digit numeric
* #return {String}
*/
translateNAICS: function(inNAICS) {
inNAICS = inNAICS || "000";
if (obj.hasOwnProperty(inNAICS)) { return obj[inNAICS] };
return "Unknown";
}
};
However, when I try to use this in a project, the code seems to look for codes.js in the project's root rather than in the modules root. I was able to prove this by making a copy of codes.js and putting it in the project's root and everything worked as expected.
So what is the proper way to include the data from codes.js so that it is available to my two functions?
The easiest way is to simply require it via a relative path name:
var obj = require('./codes.json');
Requires are always relative to the module itself, not the current working directory. Node.js understand that this is a JSON file and parses it accordingly.
In general, you can get a reference to the directory the module is in via the __dirname variable. So the following works as well:
var path = require('path');
var obj = JSON.parse(fs.readFileSync(path.join(__dirname, 'codes.json'), 'utf8'));
I would like to run an executable and its path contains an enviroment variable, for example if I would like to run chrome.exe I would like to write something like this
var spawn = require('child_process').spawn;
spawn('chrome',[], {cwd: '%LOCALAPPDATA%\\Google\\Chrome\\Application', env: process.env})
instead of
var spawn = require('child_process').spawn;
spawn('chrome',[], {cwd: 'C:\\Users\myuser\\AppData\\Local\\Google\\Chrome\\Application', env: process.env}).
Is there a package I can use in order to achieve this?
You can use a regex to replace your variable with the relevant property of process.env :
let str = '%LOCALAPPDATA%\\Google\\Chrome\\Application'
let replaced = str.replace(/%([^%]+)%/g, (_,n) => process.env[n])
I don't think a package is needed when it's a one-liner.
I realize that the question is asking for Windows environment variables, but I modified #Denys Séguret's answer to handle bash's ${MY_VAR} and $MY_VAR style formats as I thought it might be useful for others who came here.
Note: the two arguments are because there are two groupings based on the variations of the format.
str.replace(/\$([A-Z_]+[A-Z0-9_]*)|\${([A-Z0-9_]*)}/ig, (_, a, b) => process.env[a || b])
Adding a TypeScript friendly addition to the excellent answer by Denys Séguret:
let replaced = str.replace(/%([^%]+)%/g, (original, matched) => {
const r = Process.env[matched]
return r ? r : ''
})
Here is a generic helper function for this:
/**
* Replaces all environment variables with their actual value.
* Keeps intact non-environment variables using '%'
* #param {string} filePath The input file path with percents
* #return {string} The resolved file path
*/
function resolveWindowsEnvironmentVariables (filePath) {
if (!filePath || typeof(filePath) !== 'string') {
return '';
}
/**
* #param {string} withPercents '%USERNAME%'
* #param {string} withoutPercents 'USERNAME'
* #return {string}
*/
function replaceEnvironmentVariable (withPercents, withoutPercents) {
let found = process.env[withoutPercents];
// 'C:\Users\%USERNAME%\Desktop\%asdf%' => 'C:\Users\bob\Desktop\%asdf%'
return found || withPercents;
}
// 'C:\Users\%USERNAME%\Desktop\%PROCESSOR_ARCHITECTURE%' => 'C:\Users\bob\Desktop\AMD64'
filePath = filePath.replace(/%([^%]+)%/g, replaceEnvironmentVariable);
return filePath;
}
Can be called from anywhere
Does basic type checking first, you may want to change what is returned by default in the first if block
Functions are named in ways that explain what they do
Variables are named in ways that explain what they are
Comments added make it clear what outcomes can occur
Handles non-environment variables wrapped in percents, since the Windows file system allows for folders to be named %asdf%
JSDoc blocks for automated documentation, type checking, and auto-complete in certain editors
You may also want to use if (process.platform !== 'win32') {} depending on your need
These answers are crazy. Just can use path:
const folder = require('path').join(
process.env.LOCALAPPDATA,
'Google/Chrome/Application',
);
console.log(folder); // C:\Users\MyName\AppData\Local\Google\Chrome\Application
On Linux/MacOS, I spawn a process to resolve paths with env variables, is safe - let bash to do the work for you. Obviously less performant, but a lot more robust. Looks like this:
import * as cp from 'child_process';
// mapPaths takes an array of paths/strings with env vars, and expands each one
export const mapPaths = (searchRoots: Array<string>, cb: Function) => {
const mappedRoots = searchRoots.map(function (v) {
return `echo "${v}"`;
});
const k = cp.spawn('bash');
k.stdin.end(mappedRoots.join(';'));
const results: Array<string> = [];
k.stderr.pipe(process.stderr);
k.stdout.on('data', (d: string) => {
results.push(d);
});
k.once('error', (e) => {
log.error(e.stack || e);
cb(e);
});
k.once('exit', code => {
const pths = results.map((d) => {
return String(d || '').trim();
})
.filter(Boolean);
cb(code, pths);
});
};