My project structure looks like this:
contracts
├── CExampleToken.sol
├── compile.js
├── create-eth-wallet.js
├── deploy.js
├── package-lock.json
├── package.json
└── node_modules
This is my code:
CExampleToken.sol
pragma solidity 0.8.9;
import "#openzeppelin/contracts/token/ERC20/ERC20.sol";
import "#openzeppelin/contracts/token/ERC20/ERC20Detailed.sol";
contract CExampleToken is ERC20 {
constructor() ERC20("CExample", "CEXT") {
_mint(msg.sender, 25000000);
}
}
compile.js
const path = require('path');
const fs = require('fs');
const solc = require('solc');
const contractPath = path.resolve(__dirname, 'CExampleToken.sol');
const source = fs.readFileSync(contractPath, 'utf8');
const input = {
language: "Solidity",
sources: {
'CExampleToken.sol': {
content: source,
},
},
settings: {
outputSelection: {
'*': {
'*': ['*']
},
},
},
};
const tempFile = JSON.parse(solc.compile(JSON.stringify(input)));
console.log(tempFile);
const contractFile = tempFile.contracts['CExampleToken.sol']['CExampleToken'];
module.exports = contractFile;
deploy.js
const Web3 = require('web3');
const contractFile = require('./compile');
const bytecode = contractFile.evm.bytecode.object;
const abi = contractFile.abi;
const privKey = <my private key here>;
const address = <my address here>;
const web3 = new Web3('https://rpc.testnet.moonbeam.network');
const deploy = async () => {
const cexampletoken = new web3.eth.Contract(abi);
const cexampletokenTx = cexampletoken.deploy({
data: bytecode,
});
const createTransaction = await web3.eth.accounts.signTransaction(
{
from: address,
data: cexampletokenTx.encodeABI(),
gas: '4294967295'
},
privKey
);
const createReceipt = await web3.eth.sendSignedTransaction(
createTransaction.rawTransaction
);
console.log("Contract was sucessfully deployed at address: ", createReceipt.contractAddress);
};
deploy();
I am trying to compile and deploy by going
cd contracts
node deploy.js
But I get this error:
<myusername>#<mycomputername> contracts % node deploy.js
{
errors: [
{
component: 'general',
errorCode: '1878',
formattedMessage: 'Warning: SPDX license identifier not provided in source file. Before publishing, consider adding a comment containing "SPDX-License-Identifier: <SPDX-License>" to each source file. Use "SPDX-License-Identifier: UNLICENSED" for non-open-source code. Please see https://spdx.org for more information.\n' +
'--> CExampleToken.sol\n' +
'\n',
message: 'SPDX license identifier not provided in source file. Before publishing, consider adding a comment containing "SPDX-License-Identifier: <SPDX-License>" to each source file. Use "SPDX-License-Identifier: UNLICENSED" for non-open-source code. Please see https://spdx.org for more information.',
severity: 'warning',
sourceLocation: [Object],
type: 'Warning'
},
{
component: 'general',
errorCode: '6275',
formattedMessage: 'ParserError: Source "#openzeppelin/contracts/token/ERC20/ERC20.sol" not found: File import callback not supported\n' +
' --> CExampleToken.sol:3:1:\n' +
' |\n' +
'3 | import "#openzeppelin/contracts/token/ERC20/ERC20.sol";\n' +
' | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n' +
'\n',
message: 'Source "#openzeppelin/contracts/token/ERC20/ERC20.sol" not found: File import callback not supported',
severity: 'error',
sourceLocation: [Object],
type: 'ParserError'
},
{
component: 'general',
errorCode: '6275',
formattedMessage: 'ParserError: Source "#openzeppelin/contracts/token/ERC20/ERC20Detailed.sol" not found: File import callback not supported\n' +
' --> CExampleToken.sol:4:1:\n' +
' |\n' +
'4 | import "#openzeppelin/contracts/token/ERC20/ERC20Detailed.sol";\n' +
' | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n' +
'\n',
message: 'Source "#openzeppelin/contracts/token/ERC20/ERC20Detailed.sol" not found: File import callback not supported',
severity: 'error',
sourceLocation: [Object],
type: 'ParserError'
}
],
sources: {}
}
/Users/<myusername>/Desktop/Coding/CodingTestSpace/MoonbeamTutorial101921/contracts/compile.js:24
const contractFile = tempFile.contracts['CExampleToken.sol']['CExampleToken'];
^
TypeError: Cannot read properties of undefined (reading 'CExampleToken.sol')
at Object.<anonymous> (/Users/<myusername>/Desktop/Coding/CodingTestSpace/MoonbeamTutorial101921/contracts/compile.js:24:40)
at Module._compile (node:internal/modules/cjs/loader:1101:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Module.require (node:internal/modules/cjs/loader:1005:19)
at require (node:internal/modules/cjs/helpers:102:18)
at Object.<anonymous> (/Users/<myusername>/Desktop/Coding/CodingTestSpace/MoonbeamTutorial101921/contracts/deploy.js:2:22)
at Module._compile (node:internal/modules/cjs/loader:1101:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:79:12)
at node:internal/main/run_main_module:17:47
<myusername>#<mycomputername> contracts %
Btw, I did install openzeppelin. When I made the project I did
cd contracts
npm init
npm install solc#latest
npm install #openzeppelin/contracts
What's the problem and how do I fix it?
UPDATE
Okay I fixed the problem thanks to #ahmad-gorji
This issue was that the #openzeppelin contracts were using s different compiler so I copied the functions that #openzeppelin was supposed to import directly into my CExampleToken.sol file.
I'm getting a new error now...
RuntimeError: abort(Error: Returned error: submit transaction to pool failed: Pool(InvalidTransaction(InvalidTransaction::ExhaustsResources))). Build with -s ASSERTIONS=1 for more info.
at process.abort (/home/Coding/CodingTestSpace/MoonbeamTutorial101921/contracts/node_modules/solc/soljson.js:1:13012)
at process.emit (node:events:390:28)
at emit (node:internal/process/promises:136:22)
at processPromiseRejections (node:internal/process/promises:242:25)
at processTicksAndRejections (node:internal/process/task_queues:97:32)
at runNextTicks (node:internal/process/task_queues:65:3)
at listOnTimeout (node:internal/timers:526:9)
at processTimers (node:internal/timers:500:7)
myusername#mycompname contracts %
I think this might have to do with the moonbeam testnet rpc node though :/. This is the network I'm using in the relevant code.
const web3 = new Web3('https://rpc.testnet.moonbeam.network');
I have an application that I would like to deploy to AWS Elastic Beanstalk, but have been getting a plethora of errors. My issue is that I do not know exactly which files to bundle. I am using one of the Cesium examples with my own parameters. The .html opens fine in web browser via localhost and node.js. However when I've tried to bundle what I thought are the correct files together, I have been getting deployment errors in the logs. I want to hit the 3D Tiles Feature Styling. html in the folder structure below. I have ensured that express is in the node_modules and have tried different scenarios in compiling the files. What is the solution for this issue? I have also changed app.js to main.js per other thread suggestions.
.zip structure used to deploy
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1"> <!-- Use Chrome Frame in IE -->
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no">
<meta name="description" content="Interactive 3D Tiles styling.">
<meta name="cesium-sandcastle-labels" content="Showcases, 3D Tiles">
<title>Cesium Demo</title>
<script type="text/javascript" src="/Sandcastle-header.js"></script>
<script type="text/javascript" src="/require.js"></script>
<script type="text/javascript" src="/apps.js"></script> b
<script type="text/javascript">
require.config({
baseUrl : '../../../Source',
waitSeconds : 60
});
</script>
</head>
<body class="sandcastle-loading" data-sandcastle-bucket="bucket-requirejs.html">
<style>
#import url(/bucket.css);
</style>
<div id="cesiumContainer" class="fullSize"></div>
<div id="loadingOverlay"><h1>Loading...</h1></div>
<div id="toolbar"></div>
<script id="cesium_sandcastle_script">
function startup(Cesium) {
'use strict';
//Sandcastle_Begin
// A demo of interactive 3D Tiles styling
// Styling language Documentation: https://github.com/AnalyticalGraphicsInc/3d-tiles/tree/master/Styling
// Building data courtesy of NYC OpenData portal: http://www1.nyc.gov/site/doitt/initiatives/3d-building.page
Cesium.Ion.defaultAccessToken = 'mykey';
var viewer = new Cesium.Viewer('cesiumContainer');
// Set the initial camera view to look at Manhattan
var initialPosition = Cesium.Cartesian3.fromDegrees(-118.4912, 34.0195, 753);
var initialOrientation = new Cesium.HeadingPitchRoll.fromDegrees(21.27879878293835, -21.34390550872461, 0.0716951918898415);
viewer.scene.camera.setView({
destination: initialPosition,
orientation: initialOrientation,
endTransform: Cesium.Matrix4.IDENTITY
});
// Load the NYC buildings tileset.
var tileset = new Cesium.Cesium3DTileset({ url: Cesium.IonResource.fromAssetId(3099) });
viewer.scene.primitives.add(tileset);
// Color buildings based on their height.
function colorByHeight() {
tileset.style = new Cesium.Cesium3DTileStyle({
color: {
conditions: [
["${height} >= 300", "rgba(45, 0, 75, 0.5)"],
["${height} >= 200", "rgb(102, 71, 151)"],
["${height} >= 100", "rgb(170, 162, 204)"],
["${height} >= 50", "rgb(224, 226, 238)"],
["${height} >= 25", "rgb(252, 230, 200)"],
["${height} >= 10", "rgb(248, 176, 87)"],
["${height} >= 5", "rgb(198, 106, 11)"],
["true", "rgb(127, 59, 8)"]
]
}
});
}
// Color buildings by their total area.
function colorByArea() {
tileset.style = new Cesium.Cesium3DTileStyle({
color: "mix(color('yellow'), color('red'), min(${area} / 10000.0, 1.0))"
});
}
// Color buildings by their latitude coordinate.
function colorByLatitude() {
tileset.style = new Cesium.Cesium3DTileStyle({
color: {
conditions: [
["${latitude} >= 0.7125", "color('purple')"],
["${latitude} >= 0.712", "color('red')"],
["${latitude} >= 0.7115", "color('orange')"],
["${latitude} >= 0.711", "color('yellow')"],
["${latitude} >= 0.7105", "color('lime')"],
["${latitude} >= 0.710", "color('cyan')"],
["true", "color('blue')"]
]
}
});
}
// Color buildings by distance from a landmark.
function colorByDistance() {
tileset.style = new Cesium.Cesium3DTileStyle({
defines : {
distance : "distance(vec2(${longitude}, ${latitude}), vec2(-1.291777521, 0.7105706624))"
},
color : {
conditions : [
["${distance} > 0.0002", "color('gray')"],
["true", "mix(color('yellow'), color('green'), ${distance} / 0.0002)"]
]
}
});
}
// Color buildings with a '3' in their name.
function colorByNameRegex() {
tileset.style = new Cesium.Cesium3DTileStyle({
color : "(regExp('3').test(${name})) ? color('cyan', 0.9) : color('purple', 0.1)"
});
}
// Show only buildings greater than 200 meters in height.
function hideByHeight() {
tileset.style = new Cesium.Cesium3DTileStyle({
show : "${height} > 200"
});
}
Sandcastle.addToolbarMenu([{
text : 'Color By Height',
onselect : function() {
colorByHeight();
}
}, {
text : 'Color By Area',
onselect : function() {
colorByArea();
}
}, {
text : 'Color By Latitude',
onselect : function() {
colorByLatitude();
}
}, {
text : 'Color By Distance',
onselect : function() {
colorByDistance();
}
}, {
text : 'Color By Name Regex',
onselect : function() {
colorByNameRegex();
}
}, {
text : 'Hide By Height',
onselect : function() {
hideByHeight();
}
}]);
colorByHeight();
//Sandcastle_End
Sandcastle.finishedLoading();
}
if (typeof Cesium !== "undefined") {
startup(Cesium);
} else if (typeof require === "function") {
require(["Cesium"], startup);
}
</script>
</body>
</html>
.app js
/*eslint-env node*/
'use strict';
(function() {
var express = require('express');
var compression = require('compression');
var fs = require('fs');
var url = require('url');
var request = require('request');
var gzipHeader = Buffer.from('1F8B08', 'hex');
var yargs = require('yargs').options({
'port' : {
'default' : 3000,
'description' : 'Port to listen on.'
},
'public' : {
'type' : 'boolean',
'description' : 'Run a public server that listens on all interfaces.'
},
'upstream-proxy' : {
'description' : 'A standard proxy server that will be used to retrieve data. Specify a URL including port, e.g. "http://proxy:8000".'
},
'bypass-upstream-proxy-hosts' : {
'description' : 'A comma separated list of hosts that will bypass the specified upstream_proxy, e.g. "lanhost1,lanhost2"'
},
'help' : {
'alias' : 'h',
'type' : 'boolean',
'description' : 'Show this help.'
}
});
var argv = yargs.argv;
if (argv.help) {
return yargs.showHelp();
}
// eventually this mime type configuration will need to change
// https://github.com/visionmedia/send/commit/d2cb54658ce65948b0ed6e5fb5de69d022bef941
// *NOTE* Any changes you make here must be mirrored in web.config.
var mime = express.static.mime;
mime.define({
'application/json' : ['czml', 'json', 'geojson', 'topojson'],
'image/crn' : ['crn'],
'image/ktx' : ['ktx'],
'model/gltf+json' : ['gltf'],
'model/gltf-binary' : ['bgltf', 'glb'],
'application/octet-stream' : ['b3dm', 'pnts', 'i3dm', 'cmpt', 'geom', 'vctr'],
'text/plain' : ['glsl']
}, true);
var app = express();
app.use(compression());
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
next();
});
function checkGzipAndNext(req, res, next) {
var reqUrl = url.parse(req.url, true);
var filePath = reqUrl.pathname.substring(1);
var readStream = fs.createReadStream(filePath, { start: 0, end: 2 });
readStream.on('error', function(err) {
next();
});
readStream.on('data', function(chunk) {
if (chunk.equals(gzipHeader)) {
res.header('Content-Encoding', 'gzip');
}
next();
});
}
var knownTilesetFormats = [/\.b3dm/, /\.pnts/, /\.i3dm/, /\.cmpt/, /\.glb/, /\.geom/, /\.vctr/, /tileset.*\.json$/];
app.get(knownTilesetFormats, checkGzipAndNext);
app.use(express.static(__dirname));
function getRemoteUrlFromParam(req) {
var remoteUrl = req.params[0];
if (remoteUrl) {
// add http:// to the URL if no protocol is present
if (!/^https?:\/\//.test(remoteUrl)) {
remoteUrl = 'http://' + remoteUrl;
}
remoteUrl = url.parse(remoteUrl);
// copy query string
remoteUrl.search = url.parse(req.url).search;
}
return remoteUrl;
}
var dontProxyHeaderRegex = /^(?:Host|Proxy-Connection|Connection|Keep-Alive|Transfer-Encoding|TE|Trailer|Proxy-Authorization|Proxy-Authenticate|Upgrade)$/i;
function filterHeaders(req, headers) {
var result = {};
// filter out headers that are listed in the regex above
Object.keys(headers).forEach(function(name) {
if (!dontProxyHeaderRegex.test(name)) {
result[name] = headers[name];
}
});
return result;
}
var upstreamProxy = argv['upstream-proxy'];
var bypassUpstreamProxyHosts = {};
if (argv['bypass-upstream-proxy-hosts']) {
argv['bypass-upstream-proxy-hosts'].split(',').forEach(function(host) {
bypassUpstreamProxyHosts[host.toLowerCase()] = true;
});
}
app.get('/proxy/*', function(req, res, next) {
// look for request like http://localhost:8080/proxy/http://example.com/file?query=1
var remoteUrl = getRemoteUrlFromParam(req);
if (!remoteUrl) {
// look for request like http://localhost:8080/proxy/?http%3A%2F%2Fexample.com%2Ffile%3Fquery%3D1
remoteUrl = Object.keys(req.query)[0];
if (remoteUrl) {
remoteUrl = url.parse(remoteUrl);
}
}
if (!remoteUrl) {
return res.status(400).send('No url specified.');
}
if (!remoteUrl.protocol) {
remoteUrl.protocol = 'http:';
}
var proxy;
if (upstreamProxy && !(remoteUrl.host in bypassUpstreamProxyHosts)) {
proxy = upstreamProxy;
}
// encoding : null means "body" passed to the callback will be raw bytes
request.get({
url : url.format(remoteUrl),
headers : filterHeaders(req, req.headers),
encoding : null,
proxy : proxy
}, function(error, response, body) {
var code = 500;
if (response) {
code = response.statusCode;
res.header(filterHeaders(req, response.headers));
}
res.status(code).send(body);
});
});
var server = app.listen(argv.port, argv.public ? undefined : 'localhost', function() {
if (argv.public) {
console.log('Cesium development server running publicly. Connect to http://localhost:%d/', server.address().port);
} else {
console.log('Cesium development server running locally. Connect to http://localhost:%d/', server.address().port);
}
});
server.on('error', function (e) {
if (e.code === 'EADDRINUSE') {
console.log('Error: Port %d is already in use, select a different port.', argv.port);
console.log('Example: node server.js --port %d', argv.port + 1);
} else if (e.code === 'EACCES') {
console.log('Error: This process does not have permission to listen on port %d.', argv.port);
if (argv.port < 1024) {
console.log('Try a port number higher than 1024.');
}
}
console.log(e);
process.exit(1);
});
server.on('close', function() {
console.log('Cesium development server stopped.');
});
var isFirstSig = true;
process.on('SIGINT', function() {
if (isFirstSig) {
console.log('Cesium development server shutting down.');
server.close(function() {
process.exit(0);
});
isFirstSig = false;
} else {
console.log('Cesium development server force kill.');
process.exit(1);
}
});
})();
logs:
-------------------------------------
/var/log/nodejs/nodejs.log
-------------------------------------
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR! node server.js
npm ERR! You can get information on how to open an issue for this project with:
npm ERR! npm bugs cesium
npm ERR! Or if that isn't available, you can get their info via:
npm ERR! npm owner ls cesium
npm ERR! There is likely additional logging output above.
npm ERR! Please include the following file with any support request:
npm ERR! /var/app/current/npm-debug.log
> cesium#1.43.0 start /var/app/current
> node server.js
module.js:471
throw err;
^
Error: Cannot find module 'express'
at Function.Module._resolveFilename (module.js:469:15)
at Function.Module._load (module.js:417:25)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
at /var/app/current/server.js:4:19
at Object.<anonymous> (/var/app/current/server.js:201:3)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
npm ERR! Linux 4.9.77-31.58.amzn1.x86_64
npm ERR! argv "/opt/elasticbeanstalk/node-install/node-v6.11.5-linux-x64/bin/node" "/opt/elasticbeanstalk/node-install/node-v6.11.5-linux-x64/bin/npm" "start"
npm ERR! node v6.11.5
npm ERR! npm v3.10.10
npm ERR! code ELIFECYCLE
npm ERR! cesium#1.43.0 start: `node server.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the cesium#1.43.0 start script 'node server.js'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the cesium package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR! node server.js
npm ERR! You can get information on how to open an issue for this project with:
npm ERR! npm bugs cesium
npm ERR! Or if that isn't available, you can get their info via:
npm ERR! npm owner ls cesium
npm ERR! There is likely additional logging output above.
npm ERR! Please include the following file with any support request:
npm ERR! /var/app/current/npm-debug.log
> cesium#1.43.0 start /var/app/current
> node server.js
module.js:471
throw err;
^
Error: Cannot find module 'express'
at Function.Module._resolveFilename (module.js:469:15)
at Function.Module._load (module.js:417:25)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
at /var/app/current/server.js:4:19
at Object.<anonymous> (/var/app/current/server.js:201:3)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
npm ERR! Linux 4.9.77-31.58.amzn1.x86_64
npm ERR! argv "/opt/elasticbeanstalk/node-install/node-v6.11.5-linux-x64/bin/node" "/opt/elasticbeanstalk/node-install/node-v6.11.5-linux-x64/bin/npm" "start"
npm ERR! node v6.11.5
npm ERR! npm v3.10.10
npm ERR! code ELIFECYCLE
npm ERR! cesium#1.43.0 start: `node server.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the cesium#1.43.0 start script 'node server.js'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the cesium package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR! node server.js
npm ERR! You can get information on how to open an issue for this project with:
npm ERR! npm bugs cesium
npm ERR! Or if that isn't available, you can get their info via:
npm ERR! npm owner ls cesium
npm ERR! There is likely additional logging output above.
npm ERR! Please include the following file with any support request:
npm ERR! /var/app/current/npm-debug.log
> Elastic-Beanstalk-Sample-App#0.0.1 start /var/app/current
> node app.js
Server running at http://127.0.0.1:8081/
I'm bundling my script with Browserify + Babel like this:
function buildJs() {
let bopts = {
paths: [
`${SRC}/js`,
'./config'
],
debug: !isProduction
};
let opts = Object.assign({}, watchify.args, bopts);
let b = watchify(persistify(opts));
b.add(`${SRC}/js/index.js`)
.on('update', bundle)
.on('log', gutil.log)
.external(vendors)
.transform(babelify, {
presets: ["es2015", "react"],
plugins: [
"syntax-async-functions",
"transform-regenerator",
"transform-class-properties",
"transform-decorators-legacy",
"transform-object-rest-spread",
"transform-react-jsx-source",
staticFs
]
})
.transform(browserifyCss, { global: true });
function bundle() {
let stream = b.bundle()
.on('error', swallowError)
.on('end', () => {
gutil.log(`Building JS:bundle done.`);
})
.pipe(source('bundle.js'))
.pipe(streamify(uglify()));
return stream.pipe(gulp.dest(`${DIST}/js`));
}
return bundle();
}
It's just browserify -> babelify -> browserify-css -> uglify -> gulp.dest.
But If I ran this task, it fails with:
[17:00:30] Using gulpfile ~/ctc-web/gulpfile.js
[17:00:30] Starting 'build'...
[17:00:46] 1368516 bytes written (16.43 seconds)
[17:00:46] Building JS:bundle done.
events.js:160
throw er; // Unhandled 'error' event
^
GulpUglifyError: unable to minify JavaScript
at createError (/home/devbfex/ctc-web/node_modules/gulp-uglify/lib/create-error.js:6:14)
at wrapper (/home/devbfex/ctc-web/node_modules/lodash/_createHybrid.js:87:15)
at trycatch (/home/devbfex/ctc-web/node_modules/gulp-uglify/minifier.js:26:12)
at DestroyableTransform.minify [as _transform] (/home/devbfex/ctc-web/node_modules/gulp-uglify/minifier.js:79:19)
at DestroyableTransform.Transform._read (/home/devbfex/ctc-web/node_modules/readable-stream/lib/_stream_transform.js:159:10)
at DestroyableTransform.Transform._write (/home/devbfex/ctc-web/node_modules/readable-stream/lib/_stream_transform.js:147:83)
at doWrite (/home/devbfex/ctc-web/node_modules/readable-stream/lib/_stream_writable.js:338:64)
at writeOrBuffer (/home/devbfex/ctc-web/node_modules/readable-stream/lib/_stream_writable.js:327:5)
at DestroyableTransform.Writable.write (/home/devbfex/ctc-web/node_modules/readable-stream/lib/_stream_writable.js:264:11)
at Transform.ondata (_stream_readable.js:555:20)
Just skip uglify works, but I really need it.
The weird thing is that error was occured after end event. I tried using with vinyl-buffer, but same errors happen.
I couldn't find any solution, every my attemps fails with same error message.
What am I missing? Is there a something that I missed?
Try to replace let by var and see what happens.
I am trying to setup Stubby Server in my JavaScript environment and I am getting the error below.
The relevant part of my Gulpfile:
gulp.task('stubby', function(cb) {
var options = {
callback: function (server, options) {
server.get(1, function (err, endpoint) {
if (!err)
console.log(endpoint);
});
},
stubs: 8000,
tls: 8443,
admin: 8010,
files: [
'*.*'
]
};
stubby(options, cb);
});
The error:
[12:15:03] Starting 'stubby'...
[12:15:03] 'stubby' errored after 17 ms
[12:15:03] Error: Missing error message
at new PluginError (C:\Users\admin\IdeaProjects\myproject\node_modules\gulp-util\lib\PluginError.js:73:28)
at readJSON (C:\Users\admin\IdeaProjects\myproject\node_modules\gulp-stubby-server\index.js:90:15)
at C:\Users\admin\IdeaProjects\myproject\node_modules\gulp-stubby-server\index.js:149:24
at Array.map (native)
at stubbyPlugin (C:\Users\admin\IdeaProjects\myproject\node_modules\gulp-stubby-server\index.js:136:12)
at Gulp.<anonymous> (C:\Users\admin\IdeaProjects\myproject\gulpfile.js:54:5)
at module.exports (C:\Users\admin\IdeaProjects\myproject\node_modules\orchestrator\lib\runTask.js:34:7)
at Gulp.Orchestrator._runTask (C:\Users\admin\IdeaProjects\myproject\node_modules\orchestrator\index.js:273:3)
at Gulp.Orchestrator._runStep (C:\Users\admin\IdeaProjects\myproject\node_modules\orchestrator\index.js:214:10)
at Gulp.Orchestrator.start (C:\Users\admin\IdeaProjects\myproject\node_modules\orchestrator\index.js:134:8)
Searching the gulp-stubby-server codebase for PluginError yields the follow snippet:
function readJSON(filepath, options) {
var src = fs.readFileSync(filepath, options),
result;
if (!options.mute) {
gutil.log(gutil.colors.yellow('Parsing ' + filepath + '...'));
}
try {
result = JSON.parse(src);
return result;
} catch (e) {
throw new gutil.PluginError(PLUGIN_NAME, 'Unable to parse "' + filepath + '" file (' + e.message + ').', e);
}
}
— Source on GitHub
You can tell this is the likely culprit because of the stack trace you see, where the PluginError is coming from readJSON.
The issue
Take note of the catch block. This is caused by one of the files matching your glob (*.*) not being a valid JSON file.
To fix
Ensure you are using the newest version of gulp-stubby-server
Ensure that you are using the correct glob (that is, do you really mean *.*)
Ensure that all the files in the current working directory are valid JSON files
My Node and Npm Vesrions are below
node v6.9.1
npm v3.10.9
My code is
'use strict';
const gulp = require('gulp');
const imageop = require('gulp-image-optimization');
let dir = {
srcImages: 'public/wps/source/images',
build: 'public/wps/build/'
};
const config = {
src: dir.srcImages + '/**/*',
dest: dir.build + 'images/'
};
gulp.task('img-prod', function (cb) {
gulp.src(config.src).pipe(imageop({
optimizationLevel: 5,
progressive: true,
interlaced: true
})).pipe(gulp.dest(config.dest)).on('end', cb).on('error', cb);
});
When i do gulp build it throws an error
internal/child_process.js:289
var err = this._handle.spawn(options);
^
TypeError: Bad argument
at TypeError (native)
at ChildProcess.spawn (internal/child_process.js:289:26)
at exports.spawn (child_process.js:380:9)
at Imagemin._optimizeJpeg (/Users/sureshraju/xxx/Wps/web-pres/node_modules/image-min/imagemin.js:126:12)
at Imagemin.optimize (/Users/sureshraju/xxxx/Wps/web-pres/node_modules/image-min/imagemin.js:57:26)
at module.exports (/Users/sureshraju/xxxx/Wps/web-pres/node_modules/image-min/imagemin.js:179:21)
at /Users/sureshraju/xxxx/Wps/web-pres/node_modules/gulp-image-optimization/index.js:38:17
at FSReqWrap.oncomplete (fs.js:123:15)
Do you have svg files in your source directory?
I have just been getting the exact same problem in a project I have picked up from someone else.
I omitted svg files from the glob and the task then ran without errors.