npm start failure. $JSON.stringify.apply is not a function - json

I'm trying to run a react app but running into issues.
This is the error trace.
ERROR in Template execution failed: TypeError: $JSON.stringify.apply is not a function
ERROR in TypeError: $JSON.stringify.apply is not a function
- json-output-template.js:96 stringify
/CoD/src/origin-cms/origin-ui/ui.reactapps/src/json-output-template.js:96:26
- json-output-template.js:126 module.exports
/CoD/src/origin-cms/origin-ui/ui.reactapps/src/json-output-template.js:126:36
- index.js:265
[ui.reactapps]/[html-webpack-plugin]/index.js:265:16
- util.js:16 tryCatcher
[ui.reactapps]/[html-webpack-plugin]/[bluebird]/js/release/util.js:16:23
- promise.js:512 Promise._settlePromiseFromHandler
[ui.reactapps]/[html-webpack-plugin]/[bluebird]/js/release/promise.js:512:31
- promise.js:569 Promise._settlePromise
[ui.reactapps]/[html-webpack-plugin]/[bluebird]/js/release/promise.js:569:18
- promise.js:606 Promise._settlePromiseCtx
[ui.reactapps]/[html-webpack-plugin]/[bluebird]/js/release/promise.js:606:10
- async.js:138 Async._drainQueue
[ui.reactapps]/[html-webpack-plugin]/[bluebird]/js/release/async.js:138:12
- async.js:143 Async._drainQueues
[ui.reactapps]/[html-webpack-plugin]/[bluebird]/js/release/async.js:143:10
- async.js:17 Immediate.Async.drainQueues
[ui.reactapps]/[html-webpack-plugin]/[bluebird]/js/release/async.js:17:14
The template its trying to execute is
module.exports = function (templateParams) {
var obj = {};
obj.js = (templateParams.htmlWebpackPlugin.options.globalJs || []).concat( templateParams.htmlWebpackPlugin.files.js );
obj.css = templateParams.htmlWebpackPlugin.files.css;
return JSON.stringify(obj);
};
Application version's that I'm using
AMAC02PQ06PG8WN:ui.reactapps subhash.sulanthar$ node --version
v7.8.0
AMAC02PQ06PG8WN:ui.reactapps subhash.sulanthar$ npm --version
4.2.0
AMAC02PQ06PG8WN:ui.reactapps subhash.sulanthar$ yarn --version
0.21.3
AMAC02PQ06PG8WN:ui.reactapps subhash.sulanthar$ nvm --version
0.33.1
I've tried reinstalling node, yarn, cleared application caches, etc - all to no avail.
It all looks fine when I console the parameters from the template js:
module.exports = function (templateParams) {
var obj = {};
obj.js = (templateParams.htmlWebpackPlugin.options.globalJs || []).concat( templateParams.htmlWebpackPlugin.files.js );
obj.css = templateParams.htmlWebpackPlugin.files.css;
console.log("Object: ", obj);
console.log("JSON: ", JSON);
console.log("JSON.stringify: ", JSON.stringify);
return JSON.stringify(obj);
};
Console:
Object: { js:
[ '/etc/react-apps-chunks/b43f1ef1ef32e943333a.login-modal.js',
'/etc/react-apps-chunks/bb104a33ab4b80479b28.compare-plans.js' ],
css: [ '/etc/react-apps-chunks/ef77cfb892b9199adc95.login-modal.styles.css' ] }
JSON: {}
JSON.stringify: function stringify(it) {
// eslint-disable-line no-unused-vars
return $JSON.stringify.apply($JSON, arguments);
}
Object: { js:
[ '/etc/react-apps-chunks/react.js',
'/etc/react-apps-chunks/react-dom.js',
'/etc/react-apps-chunks/8c3d64978772b4558f5b.originReactAemIntegrator.js' ],
css: [] }
JSON: {}
JSON.stringify: function stringify(it) {
// eslint-disable-line no-unused-vars
return $JSON.stringify.apply($JSON, arguments);
}
Any idea if I'm missing something here?

Related

Using an variable object inside a Gruntfile

I'm trying to avoid duplicate code by using a variable object inside a Gruntfile with a set of specified parameters. I apologize if this is declared incorrectly, as I'm not entirely sure how to create an object variable in gruntjs. The goal is to use sonarProperties inside the sonarRunner config. In the if block, add some additional lines, and the else block, just use sonarProperties. Unfortunately my syntax is incorrect. Is this even possible? I'm basing it off of a gulpfile and would like to do something similar.
Sample gulpfile:
const packageName = require('./package.json').name;
gulp.task('sonar', callback => {
let sonarProperties = {
// #################################################
// # General Configuration
// #################################################
'sonar.projectKey': `microservice:${packageName}`,
'sonar.sourceEncoding': 'UTF-8',
'sonar.login': process.env.SONAR_TOKEN,
// #################################################
// # Javascript Configuration
// #################################################
'sonar.language': 'javascript',
'sonar.sources': 'src',
'sonar.tests': 'test',
'sonar.javascript.lcov.reportPaths': 'coverage/lcov.info',
'sonar.coverage.exclusions': 'src/**/*.spec.js',
};
if (process.env.SONAR_ANALYSIS_TYPE === 'pr') {
sonarProperties = {
...sonarProperties, // #################################################
// # Github Configuration
// #################################################
'sonar.pullrequest.provider': 'github',
'sonar.pullrequest.branch': process.env.branch,
'sonar.pullrequest.key': process.env.pr_numbers,
'sonar.pullrequest.base': process.env.base_branch,
'sonar.pullrequest.github.repository': process.env.repo,
'sonar.scm.revision': process.env.sha,
};
}
Here's the pertinent points of my gruntfile:
sonarProperties: [{
projectKey: 'microservice:<%= pkg.name %>',
projectName: 'Microservice - <%= pkg.name %>',
sourceEncoding: 'UTF-8',
login: 'admin',
password: 'admin',
host: {
url: 'http://localhost:9000/'
},
language: 'js',
sources: 'js',
tests: 'test',
testExecutionReportPaths: 'test_coverage_reporter/report.xml',
javascript: {
lcov: {
reportPaths: 'test_coverage/lcov.info'
}
},
}],
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
sonarRunner: {
analysis: {
options: {
debug: true,
separator: '\n',
sonar: (function() {
if (process.env.SONAR_ANALYSIS_TYPE === 'pr') {
return {
...sonarProperties
moreParams: someData,
};
} else {
return {
// use just sonarProperties
};
}
}())
}
}
}
});
I was able to create the function with the following:
grunt.registerTask('sonar', function () {
let sonarProperties = {
// #################################################
// # General Configuration
// #################################################
..
}
And declaring it as a callback from the beginning as a grunt task.

How to add huge number of elements from array to MySQL using Sequleize in Node.js

This is the operation going on in my method
if (result) {
const csvdata = result.body;
var csvarray = csvdata.split('\n') //array details are shown below
for (var i = 1; i <= length; i++) {
const eachdata = csvarray[i];
var symbolarray = eachdata.split(",");
const obj = {
"instrument_token": symbolarray[0],
"exchange_token": symbolarray[1],
"tradingsymbol": symbolarray[2],
"name": symbolarray[3],
"last_price": symbolarray[4],
"expiry": symbolarray[5],
"strike": symbolarray[6],
"tick_size": symbolarray[7],
"lot_size": symbolarray[8],
"instrument_type": symbolarray[9],
"segment": symbolarray[10],
"exchange": symbolarray[11]
}
db.symboltable.create(obj)
.then((response) => {
console.log("added to symbol table")
})
.catch((err) => {
console.log(err)
})
}
csvarray contains elements like :
[
"267556358,1045142,EURINR20AUGFUT,\"EURINR\",0,2020-08-27,0,0.0025,1,FUT,BCD-FUT,BCD",
"268660998,1049457,EURINR20DECFUT,\"EURINR\",0,2020-12-29,0,0.0025,1,FUT,BCD-FUT,BCD",
"266440966,1040785,EURINR20JULFUT,\"EURINR\",0,2020-07-29,0,0.0025,1,FUT,BCD-FUT,BCD",
"266073606,1039350,EURINR20JUNFUT,\"EURINR\",0,2020-06-26,0,0.0025,1,FUT,BCD-FUT,BCD",
]
it contains thousands of similar elements and when the methods calls, i am getting an error like :
D:\MEAN\node projects\Trade\controllers\apicontroller.js:135
var symbolarray = eachdata.split(",");
^
TypeError: Cannot read property 'split' of undefined
at Request._callback (D:\MEAN\node projects\Trade\controllers\apicontroller.js:135:48)
at Request.self.callback (D:\MEAN\node projects\Trade\node_modules\postman-request\request.js:268:12)
at Request.emit (events.js:311:20)
at Request.<anonymous> (D:\MEAN\node projects\Trade\node_modules\postman-request\request.js:1489:10)
at Request.emit (events.js:311:20)
at IncomingMessage.<anonymous> (D:\MEAN\node projects\Trade\node_modules\postman-request\request.js:1360:12)
at Object.onceWrapper (events.js:417:28)
at IncomingMessage.emit (events.js:323:22)
at endReadableNT (_stream_readable.js:1204:12)
at processTicksAndRejections (internal/process/task_queues.js:84:21)
[nodemon] app crashed - waiting for file changes before starting...
can anyone get me out from this issue

gulp-template (lodash) falls over with javascript templating

I am running a gulp script with gulp-template to inject values into my javascript files.
e.g.
angular
.module("<%= module %>", [
"ngRoute",
"ui.bootstrap",
"ui.select"
]);
This works fine for all the files except if I have javascript templating in the file
e.g.
function controller() {
var vm = this;
vm.getMessage = getMessage;
//------------------------------------------
function getMessage() {
if (!vm.validator)
return "";
var message = vm.validator.getMessage(vm.property);
if (message === "")
return "";
return ` *${message}`;
}
}
I then get the following error
events.js:167
throw er; // Unhandled 'error' event
^
ReferenceError: message is not defined
at eval (lodash.templateSources[10]:9:10)
at DestroyableTransform._transform (C:\andre\sourcecode\pmslogic\buildassets\node_modules\gulp-template\index.js:23:41)
at DestroyableTransform.Transform._read (C:\andre\sourcecode\pmslogic\buildassets\node_modules\through2\node_modules\readable-stre
am\lib\_stream_transform.js:184:10)
at DestroyableTransform.Transform._write (C:\andre\sourcecode\pmslogic\buildassets\node_modules\through2\node_modules\readable-str
eam\lib\_stream_transform.js:172:83)
at doWrite ([my path]node_modules\through2\node_modules\readable-stream\lib\_stream_writable.js:42
8:64)
at writeOrBuffer ([my path]node_modules\through2\node_modules\readable-stream\lib\_stream_writable
.js:417:5)
at DestroyableTransform.Writable.write ([my path]node_modules\through2\node_modules\readable-strea
m\lib\_stream_writable.js:334:11)
at write ([my path]node_modules\vinyl-fs\node_modules\readable-stream\lib\_stream_readable.js:623:
24)
at flow ([my path]node_modules\vinyl-fs\node_modules\readable-stream\lib\_stream_readable.js:632:7
)
at DestroyableTransform.pipeOnReadable ([my path]node_modules\vinyl-fs\node_modules\readable-strea
m\lib\_stream_readable.js:664:5)
Emitted 'error' event at:
at DestroyableTransform.onerror ([my path]node_modules\vinyl-fs\node_modules\readable-stream\lib\_
stream_readable.js:558:12)
at DestroyableTransform.emit (events.js:182:13)
at DestroyableTransform._transform ([my path]node_modules\gulp-template\index.js:26:9)
at DestroyableTransform.Transform._read ([my path]node_modules\through2\node_modules\readable-stre
am\lib\_stream_transform.js:184:10)
[... lines matching original stack trace ...]
at flow ([my path]node_modules\vinyl-fs\node_modules\readable-stream\lib\_stream_readable.js:632:7
)
I suspect I can solve this by passing lodash template parameters into the gulp-template call, but am stumped as to what these are.
var gulp = require("gulp");
var concat = require("gulp-concat");
var template = require('gulp-template');
...
var cfg = ????
return gulp
.src(src)
.pipe(template({ module: "test-module-name" }, cfg))
.pipe(concat(`${module}.js`))
.pipe(gulp.dest(dest));
};

How to add wavesurfer.js microphone plugin

am working angular cli am trying to add microphone plugin is not working .Let me know how to add the package.
this my code
angular.json file
scripts": ["node_modules/jquery/dist/jquery.min.js",
"node_modules/wavesurfer.js/dist/wavesurfer.js",
"node_modules/wavesurfer.js/dist/plugin/wavesurfer.microphone.min.js"]
}
****This is My .ts file where am getting error could somebody help me****
import MicrophonePlugin from 'wavesurfer.js/dist/plugin/wavesurfer.microphone.min.js';
import * as $ from 'jquery';
import * as WaveSurfer from 'wavesurfer.js';
public start() {
let wavesurfer= WaveSurfer.create({
container: '#waveform',
waveColor: 'violet',
progressColor: 'purple',
plugins: [MicrophonePlugin.create()]
});
wavesurfer.microphone.on('deviceReady', function() {
console.info('Device ready!');
});
wavesurfer.microphone.on('deviceError', function(code) {
console.warn('Device error: ' + code);
})
let microphone = WaveSurfer.Microphone; // Here am getting error microphone is undefined
microphone.create({
wavesurfer: wavesurfer
});
microphone.on('deviceReady', function(stream) {
console.log('Device ready!', stream);
});
microphone.on('deviceError', function(code) {
console.warn('Device error: ' + code);
});
// start the microphone
microphone.start();
}
There you go:
import MicrophonePlugin from 'wavesurfer.js/dist/plugin/wavesurfer.microphone.min.js';
import * as $ from 'jquery';
import * as WaveSurfer from 'wavesurfer.js';
public start() {
let wavesurfer= WaveSurfer.create({
container: '#waveform',
waveColor: 'violet',
progressColor: 'purple',
plugins: [ MicrophonePlugin.create() ]
});
wavesurfer.microphone.on('deviceReady', function (stream) {
console.info('Device ready!', stream);
});
wavesurfer.microphone.on('deviceError', function(code) {
console.warn('Device error: ' + code);
})
let microphone = wavesurfer.microphone; // you had the case wrong!
/*
You have already done all that stuff above
microphone.create({
wavesurfer: wavesurfer
});
microphone.on('deviceReady', function(stream) {
console.log('Device ready!', stream);
});
microphone.on('deviceError', function(code) {
console.warn('Device error: ' + code);
});
*/
// start the microphone
microphone.start();
}
If you want to do something with the stream (to play it back on another wavesurfer or to send it to a server), you can use a MediaRecorder:
wavesurfer: Object;
mediaRecorder: Object;
recordingBlob: Object;
public start() {
...
this.recordingBlob = null;
this.wavesurfer.microphone.on('deviceReady', function (stream) {
this.mediaRecorder = new MediaRecorder(stream);
this.mediaRecorder.onondataavailable = event => {
this.recordingBlob = event.data;
};
this.mediaRecorder.start();
});
...
}
public stop() {
if (!this.mediaRecorder || !this.wavesurfer) return;
this.mediaRecorder.stop();// triggers mediaRecorder.onondataavailable
this.mediaRecorder = null;
this.wavesurfer.stop();
}

webpack : is there a good hook / custom function to dump out resolved configuration?

I'm somewhat of a newbie with webpack and have been experimenting with easier ways to adjust/merge webpack configurations.
The following code, added to webpack/lib/webpack.js has been pretty helpful:
this is the standard webpack.js:
function webpack(options, callback) {
var compiler;
if(Array.isArray(options)) {
compiler = new MultiCompiler(options.map(function(options) {
return webpack(options);
}));
} else if(typeof options === "object") {
new WebpackOptionsDefaulter().process(options);
compiler = new Compiler();
compiler.options = options;
compiler.options = new WebpackOptionsApply().process(options, compiler);
new NodeEnvironmentPlugin().apply(compiler);
compiler.applyPlugins("environment");
compiler.applyPlugins("after-environment");
} else {
throw new Error("Invalid argument: options");
}
if(callback) {
if(typeof callback !== "function") throw new Error("Invalid argument: callback");
if(options.watch === true || (Array.isArray(options) &&
options.some(function(o) {
return o.watch;
}))) {
var watchOptions = (!Array.isArray(options) ? options : options[0]).watchOptions || {};
// TODO remove this in next major version
var watchDelay = (!Array.isArray(options) ? options : options[0]).watchDelay;
if(watchDelay) {
console.warn("options.watchDelay is deprecated: Use 'options.watchOptions.aggregateTimeout' instead");
watchOptions.aggregateTimeout = watchDelay;
}
return compiler.watch(watchOptions, callback);
}
compiler.run(callback);
}
this is my code:
//customization start
fs = require('fs');
var fnp_dump = 'webpack.dump.json';
fs.writeFile(fnp_dump, JSON.stringify(options, null, 2), function(err) {
if(err) {
return console.log(err);
}
console.log("dumping dump.webpack.js.final.json from webpack.js to: " + fnp_dump);
});
//customization end
return compiler;
}
The basic idea is that it dumps out the final json/js options object after webpack has finished sorting out the usual webpack.base.js + webpack.development.js. Since it's, at that point, just a fully-resolved javascript object, it doesn't really matter how the config.js files were written by individual developers.
Now you can diff options sent to webpack (this is an example of tranforming webpack 1 to webpack 2 configurations:
diff 003/webpack.dump.json 004/webpack.dump.json
< "loader": "style!css!postcss-loader!sass"
---
> "use": [
> {
> "loader": "style-loader"
> },
> {
> "loader": "postcss-loader"
> },
> {
> "loader": "sass-loader"
> }
> ]
However, I am customizing webpack.js directly and need to re-apply my patch after each npm update webpack. Is there a better way?
If your webpack.config.js is a function, you can call it on your own to resolve to an object.
If you have several configs (you mentioned webpack.base.js and webpack.development.js) you can use Webpack Merge to just combine your options to a single object, and then write it to the file system.
I would recommend you to have an own script in package.json to do this job, which you can then always call after your webpack job:
...,
"scripts": {
"dump-options": "scriptThatMergesConfigsAndWritesToFS.js",
"webpack-job": "webpack ... && npm run dump-options",
...
},
...
UPDATE
After some more research I realized, that the resolved options object is stored in the compiler object. The compiler object is passed to Plugins, and therefore you can easily write a Plugin that writes the config to a file, as I did here (not tested).
I also realized, that the Plugins cannot be stringified, as they are functions, so be aware of losing the Plugin configuration information.
I ended up writing my own plugin (and now notice that wtho wrote one too). It worked for me - note you need to have the bit of code that handles circular references:
// WebPackCompilationObserver.js
function WebPackCompilationObserver(options) {
WebPackCompilationObserver.options = options || {};
}
WebPackCompilationObserver.prototype.apply = function(compiler) {
compiler.plugin("emit", function(compilation, callback) {
var fs = require('fs');
var fnp_dump = WebPackCompilationObserver.options.dump_filename;
if (! fnp_dump) {
fnp_dump = "./dump.webpack.options.json";
console.log("please specify dump_filename path in the WebPackCompilationObserver.options, otherwise using default:" % fnp_dump);
}
if (fnp_dump){
console.log("dumping compilation.options to: " + fnp_dump);
var cache = [];
fs.writeFile(fnp_dump, JSON.stringify(compilation.options, function(key, value) {
if (typeof value === 'object' && value !== null) {
if (cache.indexOf(value) !== -1) {
// Circular reference found, discard key
return;
}
// Store value in our collection
cache.push(value);
}
return value;
}, 2),
function(err) {
if (err) {
return console.log(err);
}
});
cache = null;
}
callback();
});
};
module.exports = WebPackCompilationObserver;
To use it:
webpack.config.development.js:
....
var WebPackCompilationObserver = require("./WebPackCompilationObserver");
....
config.plugins = config.plugins.concat([
....
,new WebPackCompilationObserver({dump_filename: '../dumpithere.json'})
])