Node.js conditional require - javascript

Consider plugin c is supported in recent versions of Node.
What would be the best way to conditionally load it?
module.exports = {
plugins: [
require("a"),
require("b"),
[require("c"), { default: false }] //only if node version > 0.11
]
};

Make sure you add the semver package as a dependenc, then:
var semver = require("semver")
var plugins = [
require("a"),
require("b"),
];
if(semver.gt(process.version, "0.11")){
plugins.push(require("c"));
}
module.exports = {
plugins: plugins
};
This code checks for the node version using process.version, and appends the required plugin to the list if it is supported.

If you want to make sure the major part of the version number is 0 and the minor part of the version number is greater than 11 you could use this
var sem_ver = process.version.replace(/[^0-9\.]/g, '').split('.');
if(parseInt(sem_ver[0], 10) == 0 && parseInt(sem_ver[1], 10) > 11)) {
// load it
}

What you want to do is check the process object. According to the documentation, it will give you an object like so:
console.log(process.versions);
{ http_parser: '1.0',
node: '0.10.4',
v8: '3.14.5.8',
ares: '1.9.0-DEV',
uv: '0.10.3',
zlib: '1.2.3',
modules: '11',
openssl: '1.0.1e' }
Then, simply process out the node property into a conditional if in your object.

You could use process.version:
var subver = parseFloat(process.version.replace(/v/, ''));
module.exports = {
plugins: [
require("a"),
require("b"),
(subver > 0.11) [require("c"), { default: false }]
]
};

Related

Stop babel parse and generate reformatting output code

I'm using #babel/parser to read in javascript, modify it and regenerate it with babel-generator. I need to do this while retaining the javascript's formatting but it's re-formatting it. I can't see anything else in the options for the parser or generator or docs that would stop it from doing this so I'm a bit lost. Here's what I have so far.
import { parse } from '#babel/parser';
import generate from 'babel-generator';
var file = parse(script, {
sourceType: 'module',
ranges: true,
tokens: true,
plugins: ['nullishCoalescingOperator', 'typescript']
});
var script = generate(file, {
retainLines: true,
comments: true
});
console.log(script.code);
The test script I am passing it is below;
import This from 'that'
import That from './this'
export default (() => {
return Object.assign(
{},
This
{
That
}
)
})()
However generate is returning the script below;
import This from 'that'
import That from './this'
export default (() => {
return Object.assign(
{},
This
{
That });
})();
As you can see it's changing the number of spaces in a return, collapsing the end }) of the Object.assign and adding semi-colons. It will be reading in script from lots of different formats and styles and I can't change it and ideally don't want to have to provide it with an es-lint file, is there anyway to get it to print the code back out with the exact same formatting?
EDIT: the ast nodes contain the loc and range vales but it seems to be ignoring it. I'm not even sure if it's parsing it incorrectly or if the generate is ignoring it.
"loc": {
"start": {
"line": 10,
"column": 8
},
"end": {
"line": 10,
"column": 10
}
},
"range": [
319,
321
],
you need use jscodeshift, instead of babel.This library is more suitable for this scenario.
https://github.com/facebook/jscodeshift

Protractor Cucumber Configuration file throwing undefined warning for my scenarios even though those are present

my Configuration file is not able to find the spec file even though it is present in the path that i provided in the cucumberOpts..i tried all the resolutions but none of them is worked.
Config File
const log4js = require('log4js');
var fs=require('fs');
global.screenshots = require('protractor-take-screenshots-on-demand');
global.browser2;
var propertiesReader=require('properties-reader');
var env=require("../../env.js");
const {Given, Then, When, Before} = require('cucumber');
exports.config = {
//seleniumAddress: 'http://localhost:4444/wd/hub',
directConnect:true,
framework: 'custom',
// path relative to the current config file
frameworkPath: require.resolve('protractor-cucumber-framework'),
capabilities: {
'browserName': 'chrome',
metadata: {
browser: {
name: 'chrome',
version: '79'
},
device: 'MacBook Pro 15',
platform: {
name: 'OSX',
version: '10.12.6'
},
disableLog:true,
durationInMS:true,
openReportInBrowser:true
}
},
ignoreUncaughtExceptions:false,
// Spec patterns are relative to this directory.
specs: [
'../../Test_modules/features/'
],
beforeLaunch:function(){
if (fs.existsSync('./logs/ExecutionLog.log')) {
fs.unlink('./logs/ExecutionLog.log')
}
log4js.configure({
appenders: {
out: { type: 'console' },
info:{ type: 'dateFile', filename: "../Reports/logs/info", "pattern":"-dd.log",alwaysIncludePattern:false},
"console" : {
"type": "console",
"category": "console"
},
"file" : {
"category": "test-file-appender",
"type": "file",
"filename": "../../Reports/logs/log_file.log",
"maxLogSize": 10240,
// "backups": 3,
// "pattern": "%d{dd/MM hh:mm} %-5p %m"
}
},
categories: {
"info" :{"appenders": ["console"], "level": "info"},
"default" :{"appenders": ["console", "file"], "level": "DEBUG"},
//"file" : {"appenders": ["file"], "level": "DEBUG"}
}
});
},
cucumberOpts: {
require:['../../Test_modules/utilities/timeOutConfig.js','../../Test_modules/stepDefinition/spec.js'],
tags: false,
profile: false,
format:'json:../../Reports/jsonResult/results.json',
'no-source': true
},
onPrepare: function () {
const logDefault = log4js.getLogger('default');
const logInfo=log4js.getLogger('info');
screenshots.browserNameJoiner = ' - '; //this is the default
//folder of screenshot
screenshots.screenShotDirectory = '../../Screenshots';
global.openNewBrowser=require('../../Test_modules/utilities/newBrowserinstance.js');
global.testData=require('../../TestData/testData.json');
browser.logger = log4js.getLogger('protractorLog4js');
global.firstBrowser=browser;
global.properties=propertiesReader('../../TestData/propertyConfig.properties');
browser.waitForAngularEnabled(false);
browser.manage().window().maximize();
global.facebook=require('../../Test_modules/pages/fbPageObjects.js');
global.utility=require('../../Test_modules/utilities/testFile.js');
},
plugins: [{
package: 'H:/workspace/Proc-UI/node_modules/protractor-multiple-cucumber-html-reporter-plugin',
options:{
// read the options part for more options
automaticallyGenerateReport: true,
removeExistingJsonReportFile: true,
reportPath:'../../Reports/HtmlReports',
reportName:"test.html"
},
customData: {
title: 'Run info',
data: [
{label: 'Project', value: 'Framework Setup'},
{label: 'Release', value: '1.2.3'},
{label: 'Cycle', value: 'Test Cycle'}
]
},
}]
};
Spec File
var utilityInit,page2;//browser2;
page1=new facebook(firstBrowser);
module.exports=function(){
this.Given(/^Open the browser and Load the URL$/,async function(){
await firstBrowser.get(properties.get("url1"));
browser.logger.info("Title of the window is :"+await browser.getTitle());
//screenshots.takesScreenshot("filename");
});
this.When(/^User entered the text in the search box$/,async function(){
firstBrowser.sleep(3000);
await page1.email().sendKeys(testData.Login.CM[0].Username);
browser.sleep(3000);
await page1.password().sendKeys(testData.Login.CM[0].Password);
});
this.Then(/^click on login button$/,async function(){
browser.sleep(3000);
await facebook.submit().click();
});
this.Then(/^User tried to open in new browser instance$/,async function(){
browser2=await openNewBrowser.newBrowserInit(firstBrowser);
utilityInit=new utility(browser2);
utilityInit.ignoreSync(properties.get("url2"));
browser2.manage().window().maximize();
console.log(await utilityInit.title()+" title");
browser2.sleep(5000);
});
this.When(/^User entered the text in the email field$/,async function(){
page2=new facebook(browser2);
console.log(await page2.title()+" browser2");
await page2.search().sendKeys("testing");
browser2.sleep(3000);
page1=new facebook(firstBrowser);
console.log(await page1.title()+" browser1");
await page1.email().sendKeys(testData.Login.CM[0].Username);
screenshots.takeScreenshot("newScreenshot");
firstBrowser.sleep(5000);
});
};
Execution log
1) Scenario: Title of your scenario # ..\features\test.feature:24
? Given Open the browser and Load the URL
Undefined. Implement with the following snippet:
Given('Open the browser and Load the URL', function () {
// Write code here that turns the phrase above into concrete actions
return 'pending';
});
? Then User tried to open in new browser instance
Undefined. Implement with the following snippet:
Then('User tried to open in new browser instance', function () {
// Write code here that turns the phrase above into concrete actions
return 'pending';
});
? And User entered the text in the email field
Undefined. Implement with the following snippet:
Then('User entered the text in the email field', function () {
// Write code here that turns the phrase above into concrete actions
return 'pending';
});
√ After # ..\..\node_modules\protractor-cucumber-framework\lib\resultsCapturer.js:27
1 scenario (1 undefined)
3 steps (3 undefined)
0m00.004s
i tried by adding cucumber dependencies, updating from relative path to absolute path everything i did.. but none it is resolved.. previously it worked fine but in the process of updating it in to public framework file.. i updated the paths from absolute to relative path. that's it i lost my whole framework and it is continuesly saying undefined scenarios.
**For Just made me sure i ran the script by passing wrong spec file name in the cucumber opts and still it giving Undefined and that confirmed me that it is not even considering that spec file that i passed.
Simple installation makes my framework works
npm install cucumber#1.3.3 --save-dev

How do you use require() within a map function?

Looking at the docs for CouchDB 1.6.1 here, there is mention that you can use the JS require(path) function. How do you do this? The documentation says path is "A CommonJS module path started from design document root".
My design doc is called _design/data. I have uploaded an attachment to this design doc called test.js, which can be accessed at /_design/data/test.js, and contains the following code:
exports.stuff = function() {
this.getMsg = (function() {
return 'hi';
})()
}
But the following code in my map function:
function(doc) {
try {
var x = require('test.js');
} catch (e) {
emit ('error', e)
}
}
results in this error:
["error", "invalid_require_path", "Object has no property \"test.js\". {\"views\":{\"lib\":null},\"_module_cache\":{}}"]
It looks like require is looking for the path as an object in the docparam... but I don't understand why if it is.
Looking at this link, describing this feature in an older version of CouchDB, it says you can:
However, in the upcoming CouchDB 1.1.x views will be able to require modules provided they exist below the 'views' property (eg, 'views/lib/module')
And gives the following code example:
{
"_id": "_design/example",
"lib": {
// modules here would not be accessible from view functions
},
"views": {
"lib" {
// this module is accessible from view functions
"module": "exports.test = 'asdf';"
},
"commonjs": {
"map": function (doc) {
var val = require('views/lib/module').test;
emit(doc._id, val);
}
}
}
}
But this did not work for me on CouchDB 1.6.1. I get the error:
{message: "mod.current is null", fileName: "/usr/share/couchdb/server/main.js", lineNumber: 1137, stack: "([object Array],[object Object])#/usr/share/couchdb/server/main.js:1137\n([object Array],[object Object])#/usr/share/couchdb/server/main.js:1143\n([object Array],[object Object],[object Object])#/usr/share/couchdb/server/main.js:1143\n(\"views/lib/module\")#/usr/share/couchdb/server/main.js:1173\n([object Object])#undefined:3\n([object Object])#/usr/share/couchdb/server/main.js:1394\n()#/usr/share/couchdb/server/main.js:1562\n#/usr/share/couchdb/server/main.js:1573\n"
In your question you didn't provide the function as a string. It's not too easy to spot, but you must stringify functions before storing them in CouchDB (manually or by using .toString()). Caolan has that error in the post that you linked.
Using this example:
15 views: {
16 lib: {
17 foo: "exports.bar = 42;"
18 },
19 test: {
20 map: "function(doc) { emit(doc._id, require('views/lib/foo').bar); }"
21 }
22 }
Found in older CouchDB docs here: https://wiki.apache.org/couchdb/CommonJS_Modules
I got an example working. Not sure what the difference was really... I was running 'temp' views instead of saving but I don't know why that would have effected the require statement

How to convert JSON to YAML in javascript

I want to convert a json string to yaml format in javascript.I am trying my hand on google from last two days didnt found any solution or libraries.
There are answers available for java but not for javascript.
Suppose i have json string like this:
{
"json": [
"fat and rigid"
],
"yaml": [
"skinny and flexible"
],
"object": {
"array": [
{
"null_value": null
},
{
"boolean": true
},
{
"integer": 1
}
]
}
}
conver to yaml:
json:
- fat and rigid
yaml:
- skinny and flexible
object:
array:
- null_value:
- boolean: true
- integer: 1
There is a online converter http://www.json2yaml.com/ , but how to convert to it in javascript.
You can use yaml NPM package.
const YAML = require('yaml');
const jsonObject = {
version: "1.0.0",
dependencies: {
yaml: "^1.10.0"
},
package: {
exclude: [ ".idea/**", ".gitignore" ]
}
}
const doc = new YAML.Document();
doc.contents = jsonObject;
console.log(doc.toString());
Output
version: 1.0.0
dependencies:
yaml: ^1.10.0
package:
exclude:
- .idea/**
- .gitignore
Use the 'js-yaml' npm package! That's the one that is officially recognized by yaml.org. (If you want to be extra sure && this post is outdated, go check yaml.org yourself to see which package it recommends.) I initially used 'json2yaml' instead and got strange parsing behavior when converting json (as string) to yaml.
If someone still wants to convert JSON to YAML, you may use this JavaScript library:
https://www.npmjs.com/package/json2yaml
I tried to package the answer to a bash script.
#!/bin/bash
#convert-json-to-yaml.sh
if [[ "$1" == "" ]]; then
echo "You must provide a json file in argument i.e. ./convert-json-to-yaml.sh your_file.json"
exit 1
fi
jsonFile=$1
yamlFile="$1.yaml"
if [[ "$2" != "" ]]; then
yamlFile=$2
fi
python -c 'import sys, yaml, json; yaml.safe_dump(json.load(sys.stdin), sys.stdout, default_flow_style=False)' < ${jsonFile} > ${yamlFile}
Here is how to do it :)
import * as YAML from 'yaml';
const YAMLfile = YAML.stringify(JSONFILE);
And if you want to create a YAML file, you do it with de FS.
import * as fs from 'fs';
fs.writeFileSync('./fileName.yaml', YAMLfile);

Grunt custom targets

Let's say I have 3 target modes for grunt: quick, build and dist
I also have a custom target make-stuff:
grunt.registerTask('make-stuff', [
'someCSStask',
'someUtility',
'somePackage',
'isolatedTask' // More on this below
]);
...that runs in all 3 of the above target modes (quick, build, dist) like so:
grunt.registerTask('quick', [
'some-task1',
'make-stuff'
]);
grunt.registerTask('build', [
'some-task1',
'some-task2',
'make-stuff'
]);
grunt.registerTask('dist', [
'some-task3',
'build' // make-stuff gets ran here since we reference 'build'
]);
I would like to run make-stuff normally in each target mode, except quick, where I want it to ignore isolatedTask
If this is your setup, why not move 'isolatedTask' into build?
grunt.registerTask('build', [
'some-task1',
'some-task2',
'make-stuff',
'isolatedTask'
]);
Otherwise, try something like this
grunt.registerTask(
'isolatedTask',
'Isolated tasks for make-stuff, skip if target mode is quick.',
function() {
var target = this.args[0];
if (target === 'quick') { return; }
// logic here
}
);
grunt.registerTask(
'quick',
function() {
grunt.run.tasks([
...,
'isolatedTask:' + this.nameArgs
]);
}
);

Categories

Resources