I have this simple app made using the last alpha version of Koa. In order to use `async/wait Babel.Js is required.
'use strict';
// babel registration (runtime transpilation for node)
require('./server.babel');
const Koa = require('koa');
const app = new Koa();
// define logger - this will be always executed
const logger = async (context, next) => {
const start = new Date;
await next();
const ms = new Date - start;
console.log(`${context.method} ${context.url} - ${ms}ms`);
}
const index = (context) => {
context.body = 'Hello World';
}
app.use(logger);
app.use(index);
app.listen(3000);
console.info(`The app is listening on port 3000`);
This is the hook to activate the transpiling.
const fs = require('fs');
let config;
try {
config = JSON.parse(fs.readFileSync('./.babelrc'));
} catch (error) {
console.error('==> ERROR: Error parsing your .babelrc.');
console.error(error);
}
require('babel-core/register')(config);
and this is the config file:
{
"plugins": ["transform-async-to-generator"]
}
Unfortunately when I try to run the project I get the following error:
const logger = async (context, next) => {
^
SyntaxError: Unexpected token (
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:404:25)
at Object.Module._extensions..js (module.js:432:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:313:12)
at Function.Module.runMain (module.js:457:10)
at startup (node.js:138:18)
at node.js:974:3
I have no idea why I get this error. I'm using the last Node.Js version 5.1.0 and Babel 6.2.1
You are getting the SyntaxError. That happens because your code is being parsed before Babel can intercept it and convert.
If you want to make async functions work in your first file, you should require this entire file after have registered its hook.
Create a new file start.js with the following
require('babel-register');
require('./index');
Your code in index.js can use async functions, but you can't do it in the start.js.
Also note, that you don't need to read .babelrc by yourself. Babel will do it for you by default.
Contents of .babelrc looks like this
{
"presets": [
"es2015",
"stage-3"
],
"plugins": [
[
"transform-runtime",
{
"polyfill": false,
"regenerator": true
}
]
]
}
Reference links
Async Functions with Babel
babel's require hook
upgrade nodejs version to v7.6.0 or higher
Related
I've tried to build my vue web app using this config, but I got these errors, I've tried this issue but I can't found someone got the same issue as me. How can I deal with this issue, by the way the build succeeded, the issues happened when I tried to run node src/server.jsx? Thanks in advance
$ node src/server.jsx
D:\myPathProject\node_modules\#vue\server-renderer\dist\server-renderer.cjs.js:994
vue.initDirectivesForSSR();
^
TypeError: vue.initDirectivesForSSR is not a function
at Object.<anonymous> (D:\myPathProject\node_modules\#vue\server-renderer\dist\server
-renderer.cjs.js:994:5)
at Module._compile (internal/modules/cjs/loader.js:1072:14)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1101:10)
at Module.load (internal/modules/cjs/loader.js:937:32)
at Function.Module._load (internal/modules/cjs/loader.js:778:12)
at Module.require (internal/modules/cjs/loader.js:961:19)
at require (internal/modules/cjs/helpers.js:92:18)
at Object.<anonymous> (D:\myPathProject\node_modules\#vue\server-renderer\index.js:6:
20)
at Module._compile (internal/modules/cjs/loader.js:1072:14)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1101:10)
this is my vue.config.js file
/* eslint-disable #typescript-eslint/no-var-requires */
const { WebpackManifestPlugin } = require("webpack-manifest-plugin")
const nodeExternals = require("webpack-node-externals")
exports.chainWebpack = (webpackConfig) => {
if (!process.env.VUE_APP_SSR) return
webpackConfig
.entry("app")
.clear()
.add("./src/main.server.ts")
webpackConfig.target("node")
webpackConfig.output.libraryTarget("commonjs2")
webpackConfig
.plugin("manifest")
.use(new WebpackManifestPlugin({ fileName: "ssr-manifest.json" }))
webpackConfig.externals(nodeExternals({ allowlist: /\.(css|vue)$/ }))
webpackConfig.optimization.splitChunks(false).minimize(false)
webpackConfig.plugins.delete("hmr")
webpackConfig.plugins.delete("preload")
webpackConfig.plugins.delete("prefetch")
webpackConfig.plugins.delete("progress")
webpackConfig.plugins.delete("friendly-errors")
}
and this is my server.jsx file
/* eslint-disable #typescript-eslint/no-var-requires */
const express = require("express")
const path = require("path")
const { createSSRApp } = require("vue")
const { renderToString } = require("#vue/server-renderer")
const manifest = require("../dist/ssr-manifest.json")
const server = express()
const appPath = path.join(__dirname, "../dist", manifest["app.js"])
const App = require(appPath).default
server.get("*", async (_req, res) => {
const content = createSSRApp(App)
const appContent = await renderToString(content)
const html = `
<html>
<head>
<title>Hello</title>
</head>
<body>
${appContent}
</body>
</html>
`
res.end(html)
})
server.listen(8080)
Thank you guys
Try updating your Vue 3 version.
My #vue/server-renderer package was 3.2.20 and my Vue version was 3.2.6. I bumped my Vue version to 3.2.20 and it's working great now. :)
The code is this and when I try to turn my bot on I get a error that it can't find the file to execute the command.
const fs = require('fs');
module.exports = (client, Discord) =>{
const commandFolders = fs.readdirSync('./commands')
for(const folder [enter image description here][1]of commandFolders){
const command_files = fs.readdirSync(`./commands/${folder}`).filter(file => file.endsWith('.js'))
for(const file of command_files){
const command = require(`./commands/${folder}/${file}`);
if(command.name){
client.commands.set(command.name, command);
}else {
continue
}
}
}
}
This is the error I get when I turn my bot on.
node:internal/modules/cjs/loader:944
throw err;
^
Error: Cannot find module './commands/Fun/8ball.js'
Require stack:
- C:\Users\Desktop\Discordproject\handlers\command_handler.js
- C:\Users\Desktop\Discordproject\index.js
at Function.Module._resolveFilename (node:internal/modules/cjs/loader:941:15)
at Function.Module._load (node:internal/modules/cjs/loader:774:27)
at Module.require (node:internal/modules/cjs/loader:1013:19)
at require (node:internal/modules/cjs/helpers:93:18)
at module.exports (C:\Users\Desktop\Discordproject\handlers\command_handler.js:8:25)
at C:\Users\famil\Desktop\Discordproject\index.js:11:37
at Array.forEach (<anonymous>)
at Object.<anonymous> (C:\Users\Desktop\Discordproject\index.js:10:38)
at Module._compile (node:internal/modules/cjs/loader:1109:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1138:10) {
code: 'MODULE_NOT_FOUND',
requireStack: [
'C:\\Users\Desktop\\Discordproject\\handlers\\command_handler.js',
'C:\\Users\\Desktop\\Discordproject\\index.js'
]
}
Directory Structure:
Your command_handler.js file is inside /handlers/. ./ is used to access the current directory.
Doing ./commands/ doesn't work because the commands folder is not inside of /handlers/
You must first exit the current folder (using ../), then access.
Change all of the './commands' to '../commands'
I was trying to deploy my react ssr to firebase functions and this error appeared to me, can someone help me?
i functions: Watching "C:\Users\LucasPereira\Documents\Dev\Site\ProIT\frontend\functions" for Cloud Functions...
! C:\Users\LucasPereira\Documents\Dev\Site\ProIT\frontend\functions\src\assets\gif_pro_it.gif:1
GIF89a
SyntaxError: Invalid or unexpected token
at wrapSafe (internal/modules/cjs/loader.js:1167:16)
at Module._compile (internal/modules/cjs/loader.js:1215:27)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1272:10)
at Module.load (internal/modules/cjs/loader.js:1100:32)
at Function.Module._load (internal/modules/cjs/loader.js:962:14)
at Module.require (internal/modules/cjs/loader.js:1140:19)
at require (internal/modules/cjs/helpers.js:75:18)
at Object.<anonymous> (C:\Users\LucasPereira\Documents\Dev\Site\ProIT\frontend\functions\src\pages\Home\index.js:22:42)
at Module._compile (internal/modules/cjs/loader.js:1251:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1272:10)
! We were unable to load your functions code. (see above)
This is my index.tx(root)
import * as functions from 'firebase-functions';
import React from 'react';
import { renderToString } from 'react-dom/server';
import App from './src/App';
import express from 'express';
import fs from 'fs';
const index = fs.readFileSync(__dirname + '/index.html', 'utf-8');
const app = express();
app.get('**', (req, res)=>{
const html = renderToString(<App />);
const finalHtml = index.replace('<div id="root"></div>', `<div id="root">${html}</div>`);
res.set('Cache-Control', 'public, max-age=600, s-maxage=1200');
res.send(finalHtml);
})
export let ssrapp = functions.https.onRequest(app);
This is my firebase.json
{
"hosting": {
"public": "dist",
"ignore": [
"firebase.json",
"**/.*",
"**/node_modules/**"
],
"rewrites": [
{
"source": "**",
"function": "ssrapp",
"destination": "/index.html"
}
]
},
"functions": {
"predeploy": {},
"source": "functions"
}
}
NOTE: I'm using express 4.17.1, and node version 14.
The host is working very well i'm only having problem with functions
EDIT: I change the ".gif" and it continues showing error, so I decided to remove it, only for debug, well, the error continues to another image(another PNG), the error appears to be in images
It looks like you're trying to import a *.gif image somewhere (but not in the provided code); by default, importing GIFs is not supported.
If I'm correct, then you need to setup Webpack (or its alternatives) in order to handle imports of GIF files.
I'm trying to write unit test for my electron js application and I'm stuck at one place.
For example
Lets say my app code is like below
var app= (function () {
function app() {
var _this = this;
this.open = function (data) {
var deferred = Q.defer();
try {
// some code
}
catch (ex) {
deferred.reject(ex);
}
return deferred.promise;
};
}
}());
exports.app = app
Now if I want to run it on electron client it will run perfectly fine as electron module is installed on client's PC
The problem is when I'm trying to write unit test cases for the above as electron is not installed here on dev machine like below
import { app} from '../../app'
import { Rights } from '../../Rights'
describe('app', () => {
let app: app;
beforeEach(() => {
app= new app();
})
it('should call open() and return error for null content', function (done) {
let output = app.open(null);
output
.then((res) => {
//expectation
done();
})
.catch((err)=>{
//expectation
done();
})
})
})
Getting following error
Error: Cannot find module 'electron'
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 Object.<anonymous> (<project pat>/app.js:2:16)
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)
at Function.Module._load (module.js:438:3)
npm ERR! Test failed. See above for more details.
Question
How to mock require for any module which is not installed on dev PC
but required for actual execution(installed on client's PC).
You can intercept require calls by overriding module._load :
const m = require('module');
const originalLoader = m._load;
const stubs = { electron : {} };
m._load = function hookedLoader(request, parent, isMain) {
const stub = stubs[request];
return stub || originalLoader(request, parent, isMain);
};
I have had similar issue with mocha. My basic approach was to:
* require electron in before hook,
* override it with local default
* require app
* clean in after hook
Here's a sample:
var el = require('../../modules/electron');
describe('app', function () {
'use strict';
var el_override = {
post: function () {
},
get: function () {
}
}, app;
before(function () {
/* Since we already have electron required, we override it
from node cache by:
require.cache['/path/to/file/name'].exports = el_override
*/
// Require app
// This will import overridden electron
App = require('app-location');
});
beforeEach(function () {
// init app
app = new App();
});
after(function () {
// Clean Up both electron override and app by
// delete requre.cache['/path/to/file/names']
});
it('should test for batch', function () {
// Call you functions
});
});
I am very new with MEAN stack. I am facing "TypeError: object is not a function" while starting my server > node index.js.
.../master/server/app.js:47
require('./config/socketio')(socketio);
^
TypeError: object is not a function
at Object.<anonymous> (/home/divine20/master/server/app.js:30:2)
at Module._compile (module.js:456:26)
at loader (/home/divine20/master/node_modules/babel-core/node_modules/babel-register/lib/node.js:146:5)
at Object.require.extensions.(anonymous function) [as .js] (/home/divine20/master/node_modules/babel-core/node_modules/babel-register/lib/node.js:156:7)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at Object.<anonymous> (/home/divine20/master/server/index.js:12:28)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:902:3
My Index.js file is
'use strict';
// Set default node environment to development
var env = process.env.NODE_ENV = process.env.NODE_ENV || 'development';
if (env === 'development' || env === 'test') {
// Register the Babel require hook
require('babel-core/register');
}
// Export the application
exports = module.exports = require('./app');
App.js File
/**
* Main application file
*/
'use strict';
import express from 'express';
import mongoose from 'mongoose';
mongoose.Promise = require('bluebird');
import config from './config/environment';
import http from 'http';
// Connect to MongoDB
mongoose.connect(config.mongo.uri, config.mongo.options);
mongoose.connection.on('error', function(err) {
console.error('MongoDB connection error: ' + err);
process.exit(-1);
});
// Populate databases with sample data
if (config.seedDB) { require('./config/seed'); }
// Setup server
var app = express();
var server = http.createServer(app);
var socketio = require('socket.io')(server, {
serveClient: config.env !== 'production',
path: '/socket.io-client'
});
require('./config/socketio')(socketio);
require('./config/express')(app);
require('./routes')(app);
// Start server
function startServer() {
app.angularFullstack = server.listen(config.port, config.ip, function() {
console.log('Express server listening on %d, in %s mode', config.port, app.get('env'));
});
}
setImmediate(startServer);
// Expose app
exports = module.exports = app;
// Socketio.js
/**
* Socket.io configuration
*/
'use strict';
import config from './environment';
// When the user disconnects.. perform this
function onDisconnect(socket) {
}
// When the user connects.. perform this
function onConnect(socket) {
// When the client emits 'info', this listens and executes
socket.on('info', data => {
socket.log(JSON.stringify(data, null, 2));
});
// Insert sockets below
require('../api/utility/utility.socket').register(socket);
require('../api/repayment/repayment.socket').register(socket);
require('../api/transaction/transaction.socket').register(socket);
require('../api/offer/offer.socket').register(socket);
require('../api/payment/payment.socket').register(socket);
require('../api/yelp/yelp.socket').register(socket);
require('../api/faq/faq.socket').register(socket);
require('../api/blog/blog.socket').register(socket);
require('../api/user/user.socket').register(socket);
//require('../api/listing/listing.socket').register(socket);
}
export default function(socketio) {
// socket.io (v1.x.x) is powered by debug.
// In order to see all the debug output, set DEBUG (in server/config/local.env.js) to including the desired scope.
//
// ex: DEBUG: "http*,socket.io:socket"
// We can authenticate socket.io users and access their token through socket.decoded_token
//
// 1. You will need to send the token in `client/components/socket/socket.service.js`
//
// 2. Require authentication here:
// socketio.use(require('socketio-jwt').authorize({
// secret: config.secrets.session,
// handshake: true
// }));
socketio.on('connection', function(socket) {
socket.setMaxListeners(20);
socket.address = socket.request.connection.remoteAddress +
':' + socket.request.connection.remotePort;
socket.connectedAt = new Date();
socket.log = function(...data) {
console.log(`SocketIO ${socket.nsp.name} [${socket.address}]`, ...data);
};
// Call onDisconnect.
socket.on('disconnect', () => {
onDisconnect(socket);
socket.log('DISCONNECTED');
});
// Call onConnect.
onConnect(socket);
socket.log('CONNECTED');
});
}
Thanks in advance.
You're using a default export. It's likely that whatever you're using to compile your code (e.g. Babel or TypeScript) emits a default export by adding a property onto module.exports named default.
Try to write write require('./config/socketio').default(socketio).