Giter Club home page Giter Club logo

node-w3c-validator's Introduction

node-w3c-validator

node npm license Build Status

Wrapper for The Nu Html Checker (v.Nu)

js happiness style


Attention

You need to install the "Java" for working with node-w3c-validator
Visit https://java.com for downloading the "Java" if you not have it


Table of Contents

  1. CLI
  2. Node.js API
  3. Errors and Warnings suppressing
  4. Changelog
  5. Contributing
  6. Code of Conduct

CLI

Install as global package

npm i -g node-w3c-validator

Usage

node-w3c-validator -i ./dist/*.html -f html -o ./reports/result.html -s

You may pass a glob pattern too

node-w3c-validator -i ./dist/**/*.html -f html -o ./reports/result.html -s

Options

-i, --input <path>

Validate input path.

default: process.cwd()

--exclude <path>

Exclude from input path.

default: unset

-a, --asciiquotes

Specifies whether ASCII quotation marks are substituted for Unicode smart quotation marks in messages.

default: unset

-e, --errors-only

Specifies that only error-level messages and non-document-error messages are reported (so that warnings and info messages are not reported).

default: unset, all message reported, including warnings & info messages

-q, --exit-zero-always

Makes the checker exit zero even if errors are reported for any documents

-f, --format <format>

Specifies the output format for reporting the results

default: unset possible values: gnu | xml | json | text | html | lint

lint format is available from 1.4.0 version.
lint format is designed for convenient error output to the terminal.
it uses a eslint-formatter-pretty under the hood

lint format screenshot

--filterfile <filename>

Specifies a filename. Each line of the file contains either a regular expression or starts with "#" to indicate the line is a comment. Any error message or warning message that matches a regular expression in the file is filtered out (dropped/suppressed)

default: unset, checker does no message filtering

--filterpattern <pattern>

Specifies a regular-expression pattern. Any error message or warning message that matches the pattern is filtered out (dropped/suppressed)

default: unset, checker does no message filtering

-s, --skip-non-html

Skip documents that don’t have *.html, *.htm, *.xhtml, or *.xht extensions.

default: unset, all documents found are checked, regardless of extension

-H, --html

Forces any *.xhtml or *.xht documents to be parsed using the HTML parser.

default: unset, XML parser is used for *.xhtml and *.xht documents

--no-langdetect

Disables language detection, so that documents are not checked for missing or mislabeled html[lang] attributes.

default: unset, language detection & html[lang] checking are performed

--no-stream

Forces all documents to be be parsed in buffered mode instead of streaming mode (causes some parse errors to be treated as non-fatal document errors instead of as fatal document errors).

default: unset, non-streamable parse errors cause fatal document errors

-v, --verbose

Specifies "verbose" output. (Currently this just means that the names of files being checked are written to stdout.)

default: unset, output is not verbose

-V, --version

Shows the current version number.

-o, --output <path>

Write reporting result to the path

-b, --buffersize <size>

Increase maxBuffer size to prevent !!! OUTPUT ERROR or Unexpected end of JSON input errors. This is because child_process stdout being truncated when validator check a lot of files.

CLI -b, --buffersize
# increase buffer size (1024 * 500)
node-w3c-validator -i static/**/*.html -b 500
Node.js API exec.buffersize
// increase buffer size (1024 * 500)
nodeW3CValidator(validatePath, {
    format: 'html',
    exec: {
        buffersize: 1024 * 500
    }
}, function (err, output) {
    // ...
});

Node.js API

Install in your project

npm i --save-dev node-w3c-validator

nodeW3CValidator(pathTo, options, done);

Parameters:

Name Data type Description
pathTo string The path to the folder or directly to the file, for verification, also it can be url to the Web document
options Object Options for validating, sеe description below
done Function Validation callback, sеe description below

options

You can use all available options from CLI / Options. Only change props name to the camelCase style, exeception --no-stream and --no-langdetect they must be declared without no part

example

  • --errors-only - errorsOnly: true
  • --no-langdetect - langdetect: false
  • --format json - format: 'json'

an exception

--buffersize 500

transforms to

exec: {
    buffersize: 1024 * 500
}

done(err, output)

Validation callback.

Parameters:

Name Data type Description
err Error / null if no errors - will be null, otherwise - Error object
output string string with reporting result, if no errors - can be as empty string

nodeW3CValidator.writeFile(filePath, outputData[, done])

Write file

Parameters:

Name Data type Argument Description
filePath string relative path to saving a file
outputData string / Buffer file output content
done Function optional if exist - it will asynchronous writes output to the filePath. See fs.writeFile(file, data, callback)

Usage Example

// imports
const nodeW3CValidator = require('node-w3c-validator');

// paths
const validatePath = './dist/*.html';
// or directly to the file - './dist/index.html'
// or a glob pattern - './dist/**/*.html'
const resultOutput = './reports/result.html';

// validate
nodeW3CValidator(validatePath, {
    format: 'html',
    skipNonHtml: true,
    verbose: true
}, function (err, output) {
    if (err === null) {
        return;
    }
    nodeW3CValidator.writeFile(resultOutput, output);
});

Errors and Warnings suppressing

You can ignore some errors or warnings by suppressing them.
Note! This feature can be used only on html, json and lint formats.

You need to specify nodeW3Cvalidator field in your project package.json file.

Here can be two arrays, for errors (suppressErrors) and warnigns(suppressWarnings).
Values must be a string parts or fully value of "unwanted" message.
Under the hood - node-w3c-validator will use String.protorype.includes
method for filtering messages.

For example, you receive warning message:

The “type” attribute for the “style” element is not needed and should be omitted.

Now you can suppress it

{
  "nodeW3Cvalidator": {
    "suppressErrors": [],
    "suppressWarnings": [
      "The “type” attribute for the “style” element is not needed and should be omitted."
    ]
  }
}

Or like this with a part of message:

{
  "nodeW3Cvalidator": {
    "suppressErrors": [],
    "suppressWarnings": [
      "is not needed and should be omitted"
    ]
  }
}

Changelog

See Releases history

Contributing

Please read CONTRIBUTING.md

Contributors 💪

Code of Conduct

Please read CODE_OF_CONDUCT.md

node-w3c-validator's People

Contributors

dependabot[bot] avatar detj avatar mischah avatar olehdutchenko avatar wezomdev avatar yunusga avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

node-w3c-validator's Issues

Node sdout buffer size limits (stdout being truncated)

Problem

If we have many templates, some times happens #3, !!! OUTPUT ERROR or Unexpected end of JSON input errors. This is child_process stdout being truncated.

Solution

If increase buffer size in lib/validator.js with option { maxBuffer: 1024 * 500 } all works.

// console.log(execPath.join(' '));
exec(execPath.join(' '), { maxBuffer: 1024 * 500 }, function (err, stdout, stderr) {
    let output = stdout;
    // ...

Proposal

Add option for setup maxBuffer if needed.

Support for multiple input files

How about supporting minimatch style glob patterns for the -i flag ?

vnu-jar supports multiple files as input, but node-w3c-validator only supports a single path as input.

Repeating -i flags also doesn't work because commander reads only the last -i value.

With minimatch, we can expand the list of files to the vnu-jar exec command string like this...

 java -jar ~/vnu.jar FILE.html FILE2.html FILE3.HTML FILE4.html...

I have this need to run node-w3c-validator for all HTML files in the build directory generated by gatsby and then hook this up to an npm script so that I can anytime invoke npm run validate for all markup validation needs.

<img> loading attribute

Hi everyone!
I get the error "Attribute “loading” not allowed on element “img” at this point.", but this is already part of the standard
I can fix this using the "suppressErrors: ["Attribute “loading” not allowed on element “img” at this point."]" rule in my package.json but I do not want to clutter this 😤

Any ideas on how to fix this? Thanks 🙂

Ps. validator.w3.org allows it

Running node-w3c-validator throw error

This is following error message

⠴ node-w3c-validator - processing ...undefined:1
{"messages":[{"type":"error","url":"file:/vagrant/var/export/ernaehrung_rezepte.html","lastLine":37,"lastColumn":36,"firstColumn":21,"message":"Bad value “” for attribute “action” on element “form”: Must be non-empty.","extract":"          <form action=\"\">\n     ","hiliteStart":10,"hiliteLength":16},{"type":"error","url":"file:/vagrant/var/export/ernaehrung_rezepte.html","lastLine":39,"lastColumn":68,"firstColumn":29,"message":"Any “input” descendant of a “label” element with a “for” attribute must have an ID value that matches that “for” attribute.","extract":"          <input type=\"text\" name=\"chargennummer\">\n     ","hiliteStart":10,"hiliteLength":40},{"type":"error","url":"file:/vagrant/var/export/ernaehrung_rezepte.html","lastLine":50,"lastColumn":40,"firstColumn":25,"message":"Bad value “” for attribute “action” on element “form”: Must be non-empty.","extract":"          <form action=\"\">\n     ","hiliteStart":10,"hiliteLength":16},{"type":"er

SyntaxError: Unexpected end of JSON input
    at JSON.parse (<anonymous>)
    at renderHtml (/vagrant/node_modules/node-w3c-validator/lib/render-html.js:56:22)
    at /vagrant/node_modules/node-w3c-validator/lib/validator.js:162:14
    at ChildProcess.exithandler (child_process.js:282:5)
    at emitTwo (events.js:126:13)
    at ChildProcess.emit (events.js:214:7)
    at maybeClose (internal/child_process.js:925:16)
    at Process.ChildProcess._handle.onexit (internal/child_process.js:209:5)

Unexpected token ? in JSON at position 7

What day am I already fighting, and I can not understand why this module does not start…
The command in package.json is like this:

"html-check": "node-w3c-validator -i src/**/*.html -f lint -b 500"

It gives an error like this when running the command:

$ npm run html-check
> [email protected] html-check
> node-w3c-validator -i src/**/*.html -f lint -b 500
✖ An error occurred while processing validator execution!
Unexpected token � in JSON at position 7

I read the last issues there, one of the answers says that if there are special characters in the file name, then there may be errors.
I checked both with and without them, it still does not work.

Unexpected Token W in JSON at position 0

I've tried running both of the following commands, getting the same error:

AEManager/tng-next-generation/ui.apps/src/main/content/jcr_root on  develop [⇣$!?]
➜ node-w3c-validator -i ./**/*.html -f html -o ./reports/result.html -s
⠙ node-w3c-validator - processing ...
Unexpected token W in JSON at position 0

AEManager/tng-next-generation/ui.apps/src/main/content/jcr_root on  develop [⇣$!?] took 4s
➜ node-w3c-validator -i . -f html -o ~/result.html -s
⠋ node-w3c-validator - processing ...
Unexpected token W in JSON at position 0

I want to run the validator on all html files in all sub-directories of jcr_root, which is why I assumed ./**/*.html would work. What am I doing wrong here?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.