Can't find module (Error: Cannot find module 'events/chat') - javascript

I am getting the following error:
internal/modules/cjs/loader.js:797
throw err;
^
Error: Cannot find module 'events/chat'
I have the following folder/file structure:
└─┬ chat
├─+─ events
| +── chat.js
| +── moderation.js
├─ index.js
But if I only call the chat.js or moderation.js file in my server.js file it works just fine.
index.js:
const chatEvent = require('events/chat');
const moderation = require('events/moderation');
module.exports = {
chatEvent,
moderation,
};

Related

How to fix "Error: ENOENT: no such file or directory - cypress plugins in jenkins"

Cypress Testing -->
I added below code to plugins/index.js , locally the test runs fine but when run on jenkins I get an error
function getConfigurationByFile(file) {
const pathToConfigFile = path.resolve(
'..',
'automation/cypress/configFiles',
`${file}.json`
);
return fs.readJson(pathToConfigFile);
}
module.exports = (on, config) => {
const file = config.env.fileConfig || 'qat';
return getConfigurationByFile(file);
};
error in jenkins -->
The function exported by the plugins file threw an error.
We invoked the function exported by /var/lib/jenkins/jenkins-agent/workspace/ui-automation/cypress/plugins/index.js, but it threw an error.
Error: ENOENT: no such file or directory, open '/var/lib/jenkins/jenkins-agent/workspace/automation/cypress/configFiles/qat.json'
I was able to fix this issue. The workspace path wasn't correct in my code.
jenkins workspace : workspace/ui-automation/cypress/
local workspace : workspace/automation/cypress
updated code :
const pathToConfigFile = path.resolve(
'..',
'ui-automation/cypress/configFiles',
`${file}.json`
);
return fs.readJson(pathToConfigFile);
}
module.exports = (on, config) => {
const file = config.env.fileConfig || 'qat';
return getConfigurationByFile(file);
};

Node Sequelize Mysql app "Encoding not recognized: 'undefined'" error

I have a simple web app which uses Sequelize with Mysql. After a long time and a series of updates I did not keep track of (it worked fine a year ago), the app now crashes upon starting the server.
I spent a couple of hours searching, but I did not find a satisfying answer. Does somebody know what's wrong?
Here is a minimal working example:
Setup
I have a basic directory structure with the following files:
+ test-nodejs
|- package.json
|- package-lock.json
|-+ node_modules
|-+ server
|- server.js
|-+ models
|- index.js
|- user.model.js
I ran npm init; npm install express; npm install sequelize in the root dir.
Code
I believe the only relevant part of the code is in server/server.js and server/models/index.js. Here it is:
server/server.js
const express = require("express");
const app = express();
const db = require("./models");
db.sequelize.sync()
app.get("/", (req, res) => {
res.json({message: "Welcome"});
});
const PORT = 8080
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`)
});
server/models/index.js
const Sequelize = require("sequelize");
const sequelize = new Sequelize("db", "user", "password", {host: 'localhost', dialect: 'mysql'});
const db = {};
db.Sequelize = Sequelize;
db.sequelize = sequelize;
db.users = require("./user.model.js")(sequelize, Sequelize); // This is actually not needed for the MWE
module.exports = db;
Output
When I run node server.js of this minimal working example, I get the following output:
Server is running on port 8080
node:internal/process/promises:246
triggerUncaughtException(err, true /* fromPromise */);
^
Error
at Query.run (/home/box/test-nodejs/node_modules/sequelize/dist/lib/dialects/mysql/query.js:52:25)
at /home/box/test-nodejs/node_modules/sequelize/dist/lib/sequelize.js:313:28
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async MySQLQueryInterface.databaseVersion (/home/box/test-nodejs/node_modules/sequelize/dist/lib/dialects/abstract/query-interface.js:69:12)
at async Sequelize.databaseVersion (/home/box/test-nodejs/node_modules/sequelize/dist/lib/sequelize.js:418:12)
at async /home/box/test-nodejs/node_modules/sequelize/dist/lib/dialects/abstract/connection-manager.js:181:31
at async ConnectionManager.getConnection (/home/box/test-nodejs/node_modules/sequelize/dist/lib/dialects/abstract/connection-manager.js:197:7)
at async /home/box/test-nodejs/node_modules/sequelize/dist/lib/sequelize.js:303:26
at async Sequelize.authenticate (/home/box/test-nodejs/node_modules/sequelize/dist/lib/sequelize.js:414:5)
at async Sequelize.sync (/home/box/test-nodejs/node_modules/sequelize/dist/lib/sequelize.js:374:7) {
name: 'SequelizeDatabaseError',
parent: Error: Encoding not recognized: 'undefined' (searched as: 'undefined')
at Object.getCodec (/home/box/test-nodejs/node_modules/mysql2/node_modules/iconv-lite/lib/index.js:104:23)
at Object.getEncoder (/home/box/test-nodejs/node_modules/mysql2/node_modules/iconv-lite/lib/index.js:115:23)
at Object.exports.encode (/home/box/test-nodejs/node_modules/mysql2/lib/parsers/string.js:23:25)
at Query.toPacket (/home/box/test-nodejs/node_modules/mysql2/lib/packets/query.js:16:30)
at Query.start (/home/box/test-nodejs/node_modules/mysql2/lib/commands/query.js:60:38)
at Query.execute (/home/box/test-nodejs/node_modules/mysql2/lib/commands/command.js:45:22)
at Connection.handlePacket (/home/box/test-nodejs/node_modules/mysql2/lib/connection.js:456:32)
at Connection.addCommand (/home/box/test-nodejs/node_modules/mysql2/lib/connection.js:478:12)
at Connection.query (/home/box/test-nodejs/node_modules/mysql2/lib/connection.js:546:17)
at results (/home/box/test-nodejs/node_modules/sequelize/dist/lib/dialects/mysql/query.js:60:22) {
sql: 'SELECT VERSION() as `version`',
parameters: undefined
},
original: Error: Encoding not recognized: 'undefined' (searched as: 'undefined')
at Object.getCodec (/home/box/test-nodejs/node_modules/mysql2/node_modules/iconv-lite/lib/index.js:104:23)
at Object.getEncoder (/home/box/test-nodejs/node_modules/mysql2/node_modules/iconv-lite/lib/index.js:115:23)
at Object.exports.encode (/home/box/test-nodejs/node_modules/mysql2/lib/parsers/string.js:23:25)
at Query.toPacket (/home/box/test-nodejs/node_modules/mysql2/lib/packets/query.js:16:30)
at Query.start (/home/box/test-nodejs/node_modules/mysql2/lib/commands/query.js:60:38)
at Query.execute (/home/box/test-nodejs/node_modules/mysql2/lib/commands/command.js:45:22)
at Connection.handlePacket (/home/box/test-nodejs/node_modules/mysql2/lib/connection.js:456:32)
at Connection.addCommand (/home/box/test-nodejs/node_modules/mysql2/lib/connection.js:478:12)
at Connection.query (/home/box/test-nodejs/node_modules/mysql2/lib/connection.js:546:17)
at results (/home/box/test-nodejs/node_modules/sequelize/dist/lib/dialects/mysql/query.js:60:22) {
sql: 'SELECT VERSION() as `version`',
parameters: undefined
},
sql: 'SELECT VERSION() as `version`',
parameters: {}
}
Environment
$ mysql --version
Ver 8.0.27-0ubuntu0.20.04.1 for Linux on x86_64 ((Ubuntu))
$ node --version
v16.13.1
$ npm --version
8.3.0
$ npm list
test-nodejs#1.0.0 /home/box/test-nodejs
├── express#4.17.2
├── mysql2#2.3.3
└── sequelize#6.12.0

How to set basePath for a static exported NextJS app

I need to build and deploy a React / NextJS app to a Weblogic J2ee server with a specific context. I have some React experience, but taking my first steps with NextJS.
Currently the build/verification steps are;
Create a vanilla NextJS app
Add a next.config.js with a module.export to change the basepath
module.exports = {
basePath: '/test'
}
Execute npm run dev the application is available on 'http://localhost:3000/test'
Add an export script to the package.json "export": "next build && next export" to support static export
Add the export below to resolve issue 21079
//https://github.com/vercel/next.js/issues/21079
module.exports = {
images: {
loader: "imgix",
path: "",
}
}
Executed npm run export to create a static HTML export. Export is completed successfully to the out folder.
When inspecting the index.html in the out folder, all references to the static content still starts with /_next/static and not with /test/_next/static.
So this can be a misinterpretation of my side, please correct me if i am wrong here.
To be able to test the vanilla app on the J2EE applicationserver it has to be packed into a war file. To accomplish this i added the file warpack/warpack.ts to the project.
const fs = require('fs');
const archiver = require('archiver');
const rimraf = require('rimraf') ;
const distFolder = 'dist' ;
const warFile = distFolder + '/test.war';
const buildFolder = 'out';
const contextRoot = 'test';
// Destroy dist folder
rimraf(distFolder, (error) => {
if (!error) {
// Create dist folder
if (!fs.existsSync(distFolder)){
fs.mkdirSync(distFolder);
}
const output = fs.createWriteStream(warFile);
const archive = archiver('zip', {});
output.on('close', () => {
console.log('war (' + warFile + ') ' + archive.pointer() + ' total bytes');
});
// write archive to output file
archive.pipe(output);
// add build folder to archive
archive.directory(buildFolder,'');
// add weblogic.xml
const weblogicXML = '<?xml version="1.0" encoding="UTF-8"?><weblogic-web-app xmlns="http://xmlns.oracle.com/weblogic/weblogic-web-app" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.oracle.com/weblogic/weblogic-web-app http://xmlns.oracle.com/weblogic/weblogic-web-app/1.2/weblogic-web-app.xsd"><weblogic-version>10.3.6</weblogic-version><context-root>' + contextRoot '</context-root><description>Test NextJS</description></weblogic-web-app>'
archive.append(weblogicXML,{ name: 'WEB-INF/weblogic.xml' });
const manifestMF = 'Manifest-Version: 1.0\nBuild-Tag: 0.0.1-SNAPSHOT\nWeblogic-Application-Version: 0.0.1-SNAPSHOT';
archive.append(manifestMF,{ name: 'META-INF/MANIFEST.MF' });
archive.finalize();
} else {
console.log('Failed to delete "' + distFolder + '" folder.') ;
process.exit(1);
};
});
Installed the required packages for webpack.ts
npm install fs --save-dev
npm install rimraf --save-dev
npm install archiver --save-dev
Added the script "warpack": "next build && next export && node warpack/warpack.ts" to build, export and pack the static app to an war.
After deployment of the war-file the page can be loaded on http://something/test but shows an empty page.
Network development tools indicate that the requests are made to the root of the application server, not to the configured basepath.
GET http://host:8001/static/css/main.09371e9d.chunk.css net::ERR_ABORTED 404 (Not Found)
GET http://host/static/js/2.0850eeb7.chunk.js net::ERR_ABORTED 404 (Not Found)
GET http://host/static/js/main.dc0c945b.chunk.js net::ERR_ABORTED 404 (Not Found)
​
Too much focus on basePath value instead on correct syntax of next.config.js.
Second module export in next.config.js overwrote first.
Wrong
module.exports = {
basePath: '/test'
}
//https://github.com/vercel/next.js/issues/21079
module.exports = {
images: {
loader: "imgix",
path: "",
}
}
Correct
module.exports = {
basePath: '/test',
assetPrefix: "/test/",
//https://github.com/vercel/next.js/issues/21079
images: {
loader: "imgix",
path: ""
}
}
You can use env check to invoke only for prod environment if you wish to like:
module.exports = {
basePath: "/test"
assetPrefix: process.env.NODE_ENV === "production" ? "/test/" : undefined,
}

How to get directory listing in Next.js on Netlify

I have a problem to get a directory listing in Next.js on Netlify. It works well on localhost, but when I deploy the site to Netlify I get this error:
{
"errorType": "Runtime.UnhandledPromiseRejection",
"errorMessage": "Error: ENOENT: no such file or directory, scandir '/opt/build/repo/storage/videos/'",
"trace": [
"Runtime.UnhandledPromiseRejection: Error: ENOENT: no such file or directory, scandir '/opt/build/repo/storage/videos/'",
" at process.<anonymous> (/var/runtime/index.js:35:15)",
" at process.emit (events.js:314:20)",
" at processPromiseRejections (internal/process/promises.js:209:33)",
" at processTicksAndRejections (internal/process/task_queues.js:98:32)"
]
}
This is my next.config.js:
module.exports = {
serverRuntimeConfig: {
PROJECT_ROOT: __dirname
},
target: 'experimental-serverless-trace'
};
This is my pages/index.js:
import fs from 'fs';
import path from 'path';
import { project_root } from '#config/app';
...
export async function getServerSideProps() {
const videosPath = path.join(project_root, './storage/videos/');
fs.readdirSync(videosPath).forEach(video => {
// Do stuff with a path...
});
...
}
And this is config/app.js:
import getConfig from 'next/config';
const { serverRuntimeConfig } = getConfig();
export const project_root = serverRuntimeConfig.PROJECT_ROOT;
I'm new to both Next.js and Netlify, so I'm not sure what is the problem. I see that path /opt/build/repo/storage/videos/ which is readdirSync reading is invalid and probably should be like var/runtime/storage/videos/, but I don't know how to fix it and make it work on both Netlify and localhost.
PS: Yes, I do have files in the storage/videos folder as well as on git, and on Netlify I installed these plugins for the project:

JavaScript d3.csv() gives Error: read ECONNRESET

I'm trying to test d3's d3.csv() csv reading function but still getting an error
{ 'Error: read ECONNRESET': ' at exports._errnoException (util.js:1050:11)' }
My test script test1.js is in react app directory.
admin:reactStockCharts jvr23$ tree -L 1
.
├── BCHARTS-BITSTAMPUSD.csv
├── README.md
├── node_modules
├── package-lock.json
├── package.json
├── public
├── reactStockCharts.sublime-project
├── reactStockCharts.sublime-workspace
├── src
└── test1.js
Testing csv file BCHARTS-BITSTAMPUSD.csv resides in the same directory. The content is as follows:
Date,Open,High,Low,Close,Volume (BTC),Volume (Currency),Weighted Price
2017-07-11,2326.12,2399.0,2242.62,2336.78,16815.9742946,39367980.6825,2341.10614068
2017-07-10,2504.0,2527.88,2261.85,2323.45,17296.3404527,41650843.7716,2408.07261429
2017-07-09,2550.13,2564.65,2500.5,2502.28,4483.14413363,11362427.9698,2534.47750755
2017-07-08,2501.46,2555.0,2462.0,2550.07,5405.89088691,13584489.5168,2512.90486637
2017-07-07,2599.01,2605.0,2475.0,2501.46,9430.6154578,23870564.3605,2531.17778658
test1.js script content:
var d3 = require("d3");
d3.csv("BCHARTS-BITSTAMPUSD.csv", function(err, data) {
console.log(err);
console.log(data[0]);
});
Executing the script then gives
admin:reactStockCharts jvr23$ node test1.js
null
{ 'Error: read ECONNRESET': ' at exports._errnoException (util.js:1050:11)' }
The d3 package was installed sucessfully via $ npm i d3 before.
I was able to fix the issue by replacing
var d3 = require("d3");
d3.csv("BCHARTS-BITSTAMPUSD.csv", function(err, data) {
console.log(err);
console.log(data[0]);
});
with full path specification
var d3 = require("d3");
d3.csv("file:///full/path/to/BCHARTS-BITSTAMPUSD.csv", function(err, data) {
console.log(err);
console.log(data);
});
var d3 = require("d3");
d3.csv("file:///full/path/to/BCHARTS-BITSTAMPUSD.csv", function(err, data) {
console.log(err);
console.log(data);
});
is not a solution for when you want to deploy it online, because the path will change. You should use a relative path, as explained here: https://coderwall.com/p/8nhqeg/relative-paths-from-the-root-in-javascript
You can use path module to get absolute URL
var path = require("path");
var d3 = require("d3");
d3.csv(path.resolve("BCHARTS-BITSTAMPUSD.csv"), function(err, data) {
console.log(err);
console.log(data);
});

Categories

Resources