How to connect plugin 'html-minifier? - node.js

The following code does not work. I am trying to connect the 'html-minifier' plugin to 'gulp' via the 'vinyl-source-stream' plugin.
Why am I doing this? I read on this page that you can connect the plugin 'browserify'. I wrote this code but it gives an error. How can I resolve it?
'use strict';
const { src, dest, series } = require('gulp')
const htmlMinify = require('html-minifier').minify;
const source = require('vinyl-source-stream');
const buffer = require('vinyl-buffer');
const options = {
includeAutoGeneratedTags: true,
removeAttributeQuotes: true,
removeComments: true,
removeRedundantAttributes: true,
removeScriptTypeAttributes: true,
removeStyleLinkTypeAttributes: true,
sortClassName: true,
useShortDoctype: true
};
const result = htmlMinify('frontend/*.html', options)
function test() {
return result.bundle()
.pipe(source('frontend/**/*.html'))
.pipe(buffer())
.pipe(dest('public'))
}
exports.build = series(test)

I wrote the following code and now the 'html-minifier' plugin can work directly in 'gulp'.
The const options variable is the 'html-minifier' plugin settings.
Then we create a function gHtmlMinify that can be run with the gulp gHtmlMinify command.
return src(...) is your html files path.
.on('data', function(file) {...} Each thread has a "data" event..
We hang the processing of the "data" event..
When the "data" event is called, the "file" object comes to us, which contains information: file name, file path, working directory and file contents.
The content of the file is represented as a read buffer file.isBuffer().
Buffer.from The raw data is stored in instances of the Buffer class.
(file.contents.toString() This file content is BUFFER.
The toString() method returns a function that represents an object. Converts to a string.
console.log ({ // Outputting the structure of what the file consists of.
contents: file.contents, // Content of the file BUFFER. The buffer is not a string!
path: file.path, // Path to the file.
cwd: file.cwd, // Current directory. "The directory where the gulp command was run".
base: file.base, // Value before asterisks i.e. app/
relative: file.relative, // Value after the asterisks i.e. filename.html
dirname: file.dirname, // File directory.
basename: file.basename, // File name.
stem: file.stem, // File name without extension.
extname: file.extname // File extension.
})
const { src, dest, series } = require('gulp');
const htmlMinify = require('html-minifier');
const options = {
includeAutoGeneratedTags: true,
removeAttributeQuotes: true,
removeComments: true,
removeRedundantAttributes: true,
removeScriptTypeAttributes: true,
removeStyleLinkTypeAttributes: true,
sortClassName: true,
useShortDoctype: true,
collapseWhitespace: true
};
function gHtmlMinify() {
return src('app/**/*.html')
.on('data', function(file) {
const buferFile = Buffer.from(htmlMinify.minify(file.contents.toString(), options))
file.contents = buferFile;
console.log(file);
return;
})
.pipe(dest('build'))
}
exports.gHtmlMinify = series(gHtmlMinify)

Related

How to remove line with expression in node.js via replace-in-file library

I have a task, I need to remove a piece of code through the replace-in-files library. let's say there is a code like 'import smth from "smth"'. it is necessary to delete the ENTIRE LINE with the expression and even the remaining empty space.
1.deleting the entire line
2.deleting an empty space in place of this line
I managed to make a text transformation through the library, but I don't know how to work with the code.
const options = {
files: './replace/**/*.js',
from: /smth/g,
to: '',
optionsForFiles: {
'ignore': [
"**/node_modules/**"
]
},
saveOldFile: false,
encoding: 'utf8',
shouldSkipBinaryFiles: true,
onlyFindPathsWithoutReplace: false,
returnPaths: true,
returnCountOfMatchesByPaths: true
}
we have project with a lot of folders. f1/ f2, f3/ f4 ....
and in this folders we have files like smth.js
in smth.js we have lines
'import library from "library" '
i need to remove this lines without leaving empty space.
WE HAVE
'import library from "library" '
//code
NEED
//code
code i have right now
const replaceInFile = require('replace-in-files');
const regFrom = "import { someFunc, } from '~utils/index.js";
const options = {
files: './replace/**/*.js',
from: regFrom,
to: ' ',
optionsForFiles: {
'ignore': [
"**/node_modules/**"
]
},
saveOldFile: false,
encoding: 'utf8',
shouldSkipBinaryFiles: true,
onlyFindPathsWithoutReplace: false,
returnPaths: true,
returnCountOfMatchesByPaths: true
}
const modifyFiles = async () => {
try {
const {
changedFiles,
countOfMatchesByPaths,
replaceInFilesOptions
} = await replaceInFile(options);
} catch (e) {
console.log('Error occurred:', error);
}
}
modifyFiles()
this code works but a i have problem with empty space

In koajs, how to verify the file type before uploading?

koaBody({
multipart: true,
formidable: {
uploadDir: ICON_FILE_PATH,
keepExtensions: true,
onPart(part) {
console.log('=====================>',part);
// // let formidable handle only non-file parts
// if (part.originalFilename === '' || !part.mimetype) {
// // used internally, please do not override!
// form._handlePart(part);
// }
},
onFileBegin: (name, file) => {
if (!fs.existsSync(ICON_FILE_PATH)) {
fs.mkdirSync(ICON_FILE_PATH);
}
},
},
}),
I want to verify the file type before saving the file, but the part does not take effect,Somebody help, thank you~

Node JS: Compile .scss file to .css and .map.css via node js script

I am new to node js, its structure and so on.
I am trying to compile a .scss file into a .css and .map.css file using a node js script.
The script sass-dev.js is defined in my package.json:
"scripts": {
"sass-dev": "node ./scripts/sass-dev.js"
},
So I can run the script via npm run sass-dev. The script itself works correctly, so it compiles the utility.scss into utility.css. But I want also that a source map utility.map.css is created. Therefore I defined sourceMap: true in the options, but no additional file is created.
So, how can I compile a .css and .map.css file from my .scss?
sass-dev.js:
const fs = require('fs');
const path = require('path');
const sass = require('sass');
const sassFile = path.join(__dirname, '../sass/utility.scss').toString();
const cssFile = path.join(__dirname, '../css/utility.css').toString();
const mapFile = path.join(__dirname, '../css/utility.map.scss').toString();
sass.render(
{
file: sassFile,
sourceMap: true,
outFile: mapFile,
},
(error, result) => {
if (!error) {
fs.writeFileSync(cssFile, result.css, function (err) {
if (err) console.log(`Error appeared while writing file "${o}".`);
});
} else {
console.log(error.formatted);
console.log(`Error appeared in "${error.file}" !\nline: ${error.line}, column: ${error.column}\n${error.status}`);
}
}
);
In node-scss, setting the file paths will not automatically write the output to the file (both CSS and mappings), it is just used for references and you have to write the output to a file just like how you did for the CSS.
Also, outFile should be the path of the generated CSS file. If you set sourceMap to true, the map file will be automatically determined (by appending .map). Otherwise you can set sourceMap directly to a string to use that.
Finally, since you are using writeFileSync, you don't have to pass a callback function, simply wrap it around in try catch.
sass.render({
file: sassFile,
outFile: cssFile,
}, (err, result) => {
if (err) {
// Handle error
return;
}
try {
fs.writeFileSync(cssFile, result.css);
fs.writeFileSync(mapFile, result.map);
} catch (e) {
// Handle error
}
});

Dynamic change protractor-result folder 'protractor-html-screenshot-reporter'

Here is my conf.js file.
var HtmlScreenshotReporter = require('protractor-jasmine2-screenshot-reporter');
var reporter = new HtmlScreenshotReporter({
dest : '/opt/src/protractor/results/',
filename : 'index.html',
showSummary : true,
showQuickLinks : true,
showConfiguration : true,
cleanDestination : true,
ignoreSkippedSpecs : false,
reportOnlyFailedSpecs : false,
captureOnlyFailedSpecs : true,
});
exports.config = {
...
// Setup the report before any tests start
beforeLaunch: function() {
return new Promise(function(resolve){
reporter.beforeLaunch(resolve);
});
},
onPrepare: function () {
reporter.dest = '/opt/src/protractor/results/' + browser.params.directory + '/';
jasmine.getEnv().addReporter(reporter);
I would like to dynamicly change the destination directory by passing arguments :
Eg :
protractor conf.js --suite=MySuiteName --browser.params.directory=MyDirectory
All reports are generated in /opt/src/protractor/results/ instead of /opt/src/protractor/results/MyDirectory
Why I can't change Destination directory?
Thanks in advance. :)
Inside protractor-jasmine2-screenshot-reporter implement, it only read the destination folder by options.dest of the passed-in options when call new HtmlScreenshotReporter(options).
Thus changing reporter.dest won't change the destination folder when generate report files
Please try below code: (delay to init reporter instance in onPrepare, in which you can get the value of CLI argument: --browser.params.directory
var HtmlScreenshotReporter = require('protractor-jasmine2-screenshot-reporter');
var reportOpts = {
dest : '/opt/src/protractor/results/',
filename : 'index.html',
showSummary : true,
showQuickLinks : true,
showConfiguration : true,
cleanDestination : true,
ignoreSkippedSpecs : false,
reportOnlyFailedSpecs : false,
captureOnlyFailedSpecs : true,
};
var reporter;
exports.config = {
onPrepare: function () {
// change reporter destination
reportOpts.dest = '/opt/src/protractor/results/' + browser.params.directory + '/';
// delay init reporter instance in onPrepare(), but beforelaunch()
reporter = new HtmlScreenshotReporter(reportOpts);
reporter.beforeLaunch(function(){
jasmine.getEnv().addReporter(reporter);
});
},
// Close the report after all tests finish
afterLaunch: function(exitCode) {
return new Promise(function(resolve){
reporter.afterLaunch(resolve.bind(this, exitCode));
});
}
};

How do I output webpack as a string using Node

I am trying to use Webpack to bundle a bunch of files. I have the following in my node code...
webpack({
entry: "./src/test",
output: {
path: __dirname,
filename: "bundle.js"
},
}, function(err, stats){
console.log("I would like to output the created js here");
})
This works fine creating a file called bundle.js but I can't figure out how to output as a string instead.
Basically what you can do is to read the file, and then work with it as you want.
e.g.
import webpack from 'webpack';
const config = require('../webpack.config');
const compiler = webpack(config);
compiler.run((err, stats) => {
const data = stats.toJson();
const app = data.assetsByChunkName.app[0] //here you can get the file name
// if you don't have chunks then you should use data.assets;
const file = fs.readFileSync('path to your output ' + app); //read the file
//now you can work with the file as you want.
});
//Basic webpack.config.js
module.exports = {
devtool: 'source-map',
entry: {
app: 'Some path' // you can have different entries.
entrie2 : ''
.... more entries
},
output: {
path: 'Some path'
}
}
Hope this help.

Resources