gulp-eslint not outputting to file - unable to properly configure writableStream - eslint

Issue - User cannot get output to print to file for gulp-lint process
Documentation Reference It is observed in the documentation that a writeableStream is a valid configuration, but regrettably it does not denote or provide clarification on how to do this....and I have tried the solution below, along with others to no avail...so am seeking any insight / support that can be provided
Observations - other users had published guidance suggesting a stream similar to this, but when attempting this 2 things are observed....
The IntelliJ IDE notes that the parameter "writable" should be updated to "writableStream"
The build output generates the file, but the file is empty, therefore I am obviously missing something with respect to configuring / establishing the stream properly
Sample Code Block
'use strict';
const {src, task} = require('gulp');
const eslint = require('gulp-eslint');
const fs =require('fs');
task('lint', () => {
return src(['**/*.js', '!**/node_modules/**', '!**/handlebars.runtime-v4.1.2.js', '!**/parsley.js', '!**/slick.js','!*SampleTests.js'])
// Runs eslint
.pipe(eslint())
// Sets the format of the console
.pipe(eslint.format('table',fs.createWriteStream('eslint-result.xml')))
// To have the process exit with an error code (1) on lint error, return the stream and pipe to failAfterError last
.pipe(eslint.failOnError()
.pipe(eslint.results(results => {
// Called once for all ESLint results.
console.log(`Total Results: ${results.length}`);
console.log(`Total Warnings: ${results.warningCount}`);
console.log(`Total Errors: ${results.errorCount}`);
}))
)
});

A new day brings new results I guess....after running a build with this configuration again it worked..much to my surprise.
Note, I am using maven as a build process, and am invoking this using the maven-frontend plugin....and it is important to note that the result file will NOT appear until AFTER the build process has finished

Related

SaxonJS on Node.js

I'm trying to run an empty simple code snippet to test SaxonJS 1.1.0 on NodeJs v8.11.1 on Windows 10.
require('./Saxon-JS-1.1.0/SaxonJS.js');
But I got this error :
PS C:\XXX\sandbox\xsl-transformation> node main.js
C:\XXX\xsl-transformation\Saxon-JS-1.1.0\SaxonJS.js:17136
setPlatform(JSTestDriver.platform);
^
ReferenceError: JSTestDriver is not defined
at initialize (C:\XXX\sandbox\xsl-transformation\Saxon-JS-1.1.0\SaxonJS.js:17136:25)
Looking at the source code, I can see :
function initialize() {
"use strict";
if (inBrowser) {
setPlatform(BrowserPlatform.platform);
saxonPrint("Saxon-JS " + getProcessorInfo().productVersion + " in browser", 0);
} else {
// Currently only Nashorn. (Later need to distinguish from Node case)
// Nashorn JSTestDriver
setPlatform(JSTestDriver.platform);
saxonPrint("Saxon-JS " + getProcessorInfo().productVersion + " in
Nashorn");
// node NodePlatform
}
if (typeof platform.initialize === "function") {
platform.initialize();
}
}
It seems Node Platform is not implemented.
However, in the documentation, it is written :
We're talking here primarily about running Saxon-JS in the browser.
However, it's also capable of running in server-side JavaScript
environments such as Node.js (not yet fully supported in this
release).
I deeply search a code snippet of SaxonJS/NodeJS but I did not find one.
Has anyone a snippet code of SaxonJS working on NodeJS ?
I'm afraid the documentation was somewhat jumping the gun. We do have users who have reported getting the code to run under Node.js, and we have done it ourselves "in the lab", but it requires source code tweaks to the issued product. As released, the code runs under two platforms, the browser platform and Nashorn (and under Nashorn, it assumes our test harness which is not released).
We're working on a version for Node.js. Doing this properly as a product needs a lot of functionality that isn't in the browser version, for example in XML parsing and serialization, debugging support, command line interfaces and APIs, etc.
Node.js Saxon-Js Instructions
This S/O question is the first listed on Google for "node.js saxon-js". So I'm answering this 4 years late because of the visibility.
[Terminal] npm install saxon-js
[IDE][xslt.js]
const saxonJs = require('saxon-js');
const fs = require('fs');
function transformDocument(source, destination, transformation, parameters) {
var xml = fs.readFileSync(source).toString()
var stylesheetParams = Object.getOwnPropertyNames(parameters)
.map(o => `QName('', '${o}') : '${parameters[o]}'`).join(",")
const html = saxonJs.XPath.evaluate(
`transform(
map {
'source-node' : parse-xml($xml),
'stylesheet-location' : $xslt,
'stylesheet-params': map {${stylesheetParams}},
'delivery-format' : 'serialized'
}
)?output`,
null,
{
params : {
'xml' : xml,
'xslt' : 'file:' + transformation
}
}
);
fs.writeFileSync(destination, html)
}
Parameters
source: xml file name
destination: output file name
transformation: xsl file name
parameters: regular json object containing any params for xslt
Characteristics
(-) extremely slow
(+) doesn't require running something on the command line every time the xslt file changes
(+) easy to use function signature based on xslt usage over the last 22 years
(+) doesn't crash
Notes
I didn't find any "Getting Started" for this. Not from Google, at least. I pieced together a working solution from multiple S/O answers.
This took me 3 hours. I hope this saves multiple developers 3 hours each.
I tried getting 'source-location' to work with a file: url, but no beans
sync I/O of course isn't necessary, it should work fine with async and nested callback functions. However, this isn't why its' slow. The xpath transform() function is quite slow, for some reason.
For some reason, this solution is stable and doesn't crash. Using Saxon-C over in Python keeps crashing, but this does not.

Jest toMatchSnapshot not throwing an exception

Most of Jest's expect(arg1).xxxx() methods will throw an exception if the comparison fails to match expectations. One exception to this pattern seems to be the toMatchSnapshot() method. It seems to never throw an exception and instead stores the failure information for later Jest code to process.
How can we cause toMatchSnapshot() to throw an exception? If that's not possible, is there another way that our tests can detect when the snapshot comparison failed?
This will work! After running your toMatchSnapshot assertion, check the global state: expect(global[GLOBAL_STATE].state.snapshotState.matched).toEqual(1);
Just spent the last hour trying to figure it out for our own tests. This doesn't feel hacky to me either, though a maintainer of Jest may be able to tell me whether accessing Symbol.for('$$jest-matchers-object') is a good idea or not. Here's a full code snippet for context:
const GLOBAL_STATE = Symbol.for('$$jest-matchers-object');
describe('Describe test', () => {
it('should test something', () => {
try {
expect({}).toMatchSnapshot(); // replace with whatever you're trying to test
expect(global[GLOBAL_STATE].state.snapshotState.matched).toEqual(1);
} catch (e) {
console.log(`\x1b[31mWARNING!!! Catch snapshot failure here and print some message about it...`);
throw e;
}
});
});
If you run a test (e.g. /Foobar.test.js) which contains a toMatchSnapshot matcher jest by default will create a snapshot file on the first run (e.g. /__snapshots__/Foobar.test.js.snap).
This first run that creates the snapshot will pass.
If you want the test to fail you need to commit the snapshot alongside with your test.
The next test builds will compare the changes you make to the committed snapshot and if they differ the test will fail.
Here is the official link to the Documentation on 'Snapshot Testing' with Jest.
One, less than ideal, way to cause toMatchSnapshot to throw an exception when there is a snapshot mismatch is to edit the implementation of toMatchSnapshot. Experienced Node developers will consider this to be bad practice, but if you are very strongly motivated to have that method throw an exception, this approach is actually easy and depending on how you periodically update your tooling, only somewhat error-prone.
The file of interest will be named something like "node_modules/jest-snapshot/build/index.js".
The line of interest is the first line in the method:
const toMatchSnapshot = function (received, testName) {
this.dontThrow && this.dontThrow(); const
currentTestName = ....
You'll want to split that first line and omit the calling of this.dontThrow(). The resulting code should look similar to this:
const toMatchSnapshot = function (received, testName) {
//this.dontThrow && this.dontThrow();
const
currentTestName = ....
A final step you might want to take is to send a feature request to the Jest team or support an existing feature request that is of your liking like the following: link

How can I capture the output of a webpack build as a string before it is written to disk?

There seems to be no output option in webpack to write the output as a string, either to a nodejs Buffer or to stdout. Googling has yielded nothing promising. Is this possible, via either configuration or 3rd-party-module?
You can write to an in-memory filesystem and read from it after compilation:
const compiler = webpack({ / options / });
const outputFileSystem = new webpack.MemoryOutputFileSystem()
compiler.outputFileSystem = outputFileSystem;
compiler.run((err, stats) => {
// Read the output later:
const content = outputFileSystem.readFileSync('...');
});
This involves calling webpack via its Node API, but the same may also be accomplished entirely in webpack.config.json by creating a custom webpack plugin that changes the compiler’s outputFileSystem on apply.
After researching, the only way I see to accomplish this would be to monkey-patch webpack's NodeOutputFileSystem.writeFile to capture the string contents.
I ended up using raw babeljs instead of webpack to get the string.

node.js issues with Meteor's file system

I have tried to figure out what i am missing from this puzzle between. Node.js and Meteor.js. Meteor is built on Node.js i know this. But Meteor doesn't not work properly with Node.js. Either I need to do 20 more steps to get the same result, which I don't know what they are. Or there is a serious bug between the two. Standalone Node.js runs the command below just fine. Running the same commands on Meteor cause errors or undefined results. Wish i had a why to solve this or they need to patch this so it will work the way it should work.
examples #1
var fs = require('fs');
fs.readFile('file.txt', 'utf8', function (err,data) {
if (err) {
return console.log(err);
}
console.log(data);
});
example #2
var jetpack = require('fs-jetpack');
var data = jetpack.read('file.txt');
console.log(data);
example #3
var fs = require ('fs');
var readMe = fs.readFileSync('file.txt', 'utf8');
console.log(readMe);
You shouldn't try to load files like this because you don't know what the folder structure looks like. Meteor creates builds from your project directory, both in development and production mode. This means that even though you have a file.txt in your project folder, it doesn't end up in the same place in the build (or it isn't even included in the build at all).
For example, your code tries to read the file from the development build folder .meteor/local/build/programs/server. However, this folder doesn't contain file.txt.
Solution: Store file.txt in the private folder of your project and use Assets.getText to read it. If you still want to use the functions from fs to load the file, you can retrieve the absolute path with Assets.absoluteFilePath.

Grunt-Karma: Use Node.js fs-framework in Jasmine Testfile

I'm writing unit-tests with the Jasmine-framework.
I use Grunt and Karma for running the Jasmine testfiles.
I simply want to load the content of a file on my local file-system (e.g. example.xml).
I thought I can do this:
var fs = require('fs');
var fileContent = fs.readFileSync("test/resources/example.xml").toString();
console.log(fileContent);
This works well in my Gruntfile.js and even in my karma.conf.js file, but not in my
Jasmine-file. My Testfile looks like this:
describe('Some tests', function() {
it('load xml file', function() {
var fs = require("fs");
fileContent = fs.readFileSync("test/resources/example.xml").toString();
console.log(fileContent);
});
});
The first error I get is:
'ReferenceError: require is not defined'.
Does not know why I cannot use RequireJS here, because I can use it
in Gruntfiel.js and even in karma.conf.js?!?!?
Okay, but when manually add require.js to the files-property in karma.conf.js-file,
then I get the following message:
Module name "fs" has not been loaded yet for context: _. Use require([])
With the array-syntax of requirejs, nothing happens.
I guess that is not possible to access Node.js functionality in Jasmine when running the
testfiles with Karma. So when Karma runs on Node.js, why is it not possible to access the 'fs'-framework of Nodejs?
Any comment/advice is welcome.
Thanks.
Your test do not work because karma - is a testrunner for client-side JavaScript (javascript who run in browser), but you want to test node.js code with it (which run on the server part). So karma just can't run server-side tests. You need different testrunner, for example take a look to jasmine-node.
Since this comes up first in the Google search, I received a similar error but wasn't using any node.js-style code in my project. Turns out the error was one of my bower components had a full copy of jasmine in it including its node.js-style code, and I had
{ pattern: 'src/**/*.js', included: false },
in my karma.conf.js.
So unfortunately Karma doesn't provide the best debugging for this sort of thing, dumping you out without telling you which file caused the issue. I had to just tear that pattern down to individual directories to find the offender.
Anyway, just be wary of bower installs, they bring a lot of code down into your project directory that you might not really care to have.
I think you're missing the point of unit testing here, because it seems to me that you're copying application logic into your test suite. This voids the point of a unit test because what it is supposed to do is run your existing functions through a test suite, not to test that fs can load an XML file. In your scenario if your XML handling code was changed (and introduced a bug) in the source file it would still pass the unit test.
Think of unit testing as a way to run your function through lots of sample data to make sure it doesn't break. Set up your file reader to accept input and then simply in the Jasmine test:
describe('My XML reader', function() {
beforeEach(function() {
this.xmlreader = new XMLReader();
});
it('can load some xml', function() {
var xmldump = this.xmlreader.loadXML('inputFile.xml');
expect(xmldump).toBeTruthy();
});
});
Test the methods that are exposed on the object you are testing. Don't make more work for yourself. :-)

Resources