const { getIo } = require('services/socketio');
const restful = require('utils/restful');
const publicApiService = require('services/publicApi');
const accessTokenMiddleware = require('middleware/accessToken');
const validateSessionCookieMiddleware = require('middleware/validateSessionCookie');
const logger = require('utils/logger');
package.json:
"scripts": {
"start": "node ./bin/www",
...
}
I get this error:
internal/modules/cjs/loader.js:796
throw err;
^
Error: Cannot find module 'services/socketio'
I tried running set NODE_PATH=./lib in terminal but it doesn't fix it.
Your local modules should start with ./ - so change it to './services/publicApi'.
Related
I am currently trying to use expect to do assertions by using const { expect } = require('#playwright/test'); but every time I get Error: Cannot find module '#playwright/test'. It is a very short script but something is wrong with that.
const { chromium } = require("playwright");
const { expect } = require('#playwright/test');
const { matchers } = require('playwright-expect');
console.log("##########", expect)
// add custom matchers
expect.extend(matchers);
(async () => {
const browser = await chromium.launch({
headless: false,
});
const page = await browser.newPage();
await page.goto("someurl");
await page.fill("input[name='userLoginId']", 'nnn');
await page.fill("input[name='password']", 'nnn');
await page.click("button[type=submit]");
})();
package.json
{
"name": "playwright",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "node ./index.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"playwright": "^1.15.1",
"playwright-expect": "^0.1.2"
}
}
The test works fine without this:
const { expect } = require('#playwright/test');
const { matchers } = require('playwright-expect');
console.log("##########", expect)
// add custom matchers
expect.extend(matchers);
And it does what I ask it to do, but now that I want to do assertions and I add that, now it does not work.
You have to install #playwright/test library:
npm i -D #playwright/test
Do not use playwright-expect library. Playwright already includes web-first assertions. Hence, there is no reason to use an additional library to extend expect.
Remove unused code:
const { matchers } = require('playwright-expect');
console.log("##########", expect)
// add custom matchers
expect.extend(matchers);
I've created an issue about the same question here https://github.com/microsoft/playwright/issues/14971 and I'll update the result when it's answered.
While trying to use playwright as a library i did run into the same error
Error: Cannot find module '#playwright/test'
To fix this error in my case the following needed to be done. The pre-condition is that playwright is already installed.
Create a node js project
Create a folder: mkdir HelloLibrary
Inside this folder create a file from the command prompt: echo var msg = 'Hello World'; console.log(msg); > app.js
Open a command prompt and run node app.js
Add playwright npm i -D playwright
Change content of app.js like code sample below
Run it again node app.js
Voila done
App.js sample
This code launches a browser and takes a screenshot
const { chromium } = require('playwright');
(async () => {
const browser = await chromium.launch({ headless: false, slowMo: 50 });
const page = await browser.newPage();
await page.goto('http://whatsmyuseragent.org/');
await page.screenshot({ path: `example.png` });
await browser.close();
})();
See also
Tutorial: Node.js for Beginners
Use playwright as a library
I am trying to make test case suite with mocha and mongodb-memory-server(as an in memory db). I am trying to implement this in the way below.
Project structure:
test runner: (in package.json)
"scripts": {
"test": "mocha 'app/**/*.spec.js' --recursive --exit"
},
So, First I need to initialise the in memory MongoDB, thats why I am using global.spec.js which looks like this,
const { MongoMemoryServer } = require("mongodb-memory-server");
const mongoose = require("mongoose");
mongoose.set("usePushEach", true);
let mongoServer;
before(async function () {
// mongod donwload on first time
this.timeout(30 * 1000);
mongoServer = new MongoMemoryServer();
const mongoUri = await mongoServer.getUri();
await mongoose.connect(mongoUri, {});
process.env.AGENDA_DB_URI = mongoUri;
});
after(function () {
mongoose.disconnect();
mongoServer.stop();
});
and a test-setup.js file which looks like this,
const { MongoMemoryServer } = require("mongodb-memory-server");
(async function() {
// trigger downloading mongodb executable on first time
const mongoServer = new MongoMemoryServer();
await mongoServer.getUri();
mongoServer.stop();
})()
.then(() => {
process.exit(0);
})
.catch(err => {
console.error(err);
process.exit(1);
});
all *.spec.js files will be inside modules folder. In simple word each folder inside module will have one .spec.js file. If I try to run this using the npm run test command it is throwing me some error, that looks like this,
1) "before all" hook
0 passing (448ms)
1 failing
1) "before all" hook:
Uncaught Error: TypeError: logWarnFn is not a function
I believe this logWarnFn error is coming from i18n. But when i start the server it is working fine.
versions:
"mongodb-memory-server": "^6.6.2",
"mocha": "^6.0.2",
"i18n": "0.8.3",
I've tried a few implementations which none have been successful.
First Attempt
Using eval in package.json script "fetch:data": "eval $(cat .env) ts-node -O '{\"module\":\"commonjs\"}' ./bin/build-api-data.ts".
This results in a JSON parsing error because eval is removing my quotes for some reason.
undefined:1
{module:commonjs}
^
SyntaxError: Unexpected token m in JSON at position 1
Second Attempt
Using dotenv, the problem I encountered here was it was a race condition resulting in errors like this:
$ CANDID_ENV=local ts-node -O '{"module":"commonjs"}' ./bin/build-api-data.ts
/Users/lassiter.gregg/code/candidco-web/node_modules/contentful/dist/webpack:/contentful/contentful.js:49
throw new TypeError('Expected parameter accessToken')
^
TypeError: Expected parameter accessToken
Code Sample
import fs from 'fs';
import path from 'path';
import fetchApiData from '../lib/apiData';
import dotEnv from 'dotenv-safe';
const { CANDID_ENV } = process.env;
const isLocalBuild = CANDID_ENV === 'local';
console.log(dotEnv);
const API_DATA_FILENAME = 'api_data.json';
const ensureDirectoryExistence = filePath => {
var dirname = path.dirname(filePath);
if (fs.existsSync(dirname)) {
return true;
}
ensureDirectoryExistence(dirname);
fs.mkdirSync(dirname);
};
const writeData = (filename, data) => {
const filePath = path.join(__dirname, '..', '.data', filename);
ensureDirectoryExistence(filePath);
fs.writeFileSync(filePath, JSON.stringify(data));
console.log('API data stored', filePath);
};
const fetchAndStoreApiData = async () => {
console.log('Fetching all API data');
await dotEnv.config({
path: isLocalBuild ? './.env' : `./.env.${CANDID_ENV}`,
});
const newData = await fetchApiData();
writeData(API_DATA_FILENAME, newData);
};
const init = async () => {
fetchAndStoreApiData();
};
if (require.main === module) {
init();
}
In the case above, I've tried doing dotenv.config at the top of the file, in the init, in the function as you see. It always throws the same error about contentful not getting the env variable it needs. That said, if I log process.env and comment out the code relevant to fetchApiData then I see all my environment variables. That's why I think it's a race-time condition but haven't been able to find anything similar to my own issue.
Additionally, what makes this even more thorny is that this is a custom script that has to work in a node and esnext environment. So, I've had my fair share of thorny import/export issues using syntax I don't really prefer but haven't found away around it (e.g. export = someFunction).
Do I see it correctly, that you are trying to configure dotenv with a variable that you initialize with an env variable? I don't think that's going to work out.
Dotenv's work is to load the env variables to process.env. You have to config it as early as possible in your app.
More about it here: https://www.npmjs.com/package/dotenv
How do I add an new file extension to Nodejs dynamic import?
I want to add my own filetype, lets call it .jszip. (No, this is just an example and what I actually want has nothing to do with zip).
Say I have
package.json:
{
"name": "test",
"scripts": {
"zip": "node --experimental-modules test.js"
}
}
test.js:
const fs = require('fs');
const Module = require('module');
function loadJsZip(module, filename) {
console.log('In loadJsZip');
const content = fs.readFileSync(filename, 'utf8');
// Do something to content
module._compile(content, filename);
}
require.extensions['.jszip'] = loadJsZip;
Module._extensions['.jszip'] = loadJsZip;
function loadJs(relativePath) {
import(f).then((module) => {
console.log(`imported from ${filename}:${module}`);
}).catch((err) => {
console.log(`While importing:${err}`);
});
}
loadJs('./testfile.jszip');
I am getting:
(node:20412) ExperimentalWarning: The ESM module loader is experimental.
While importing:TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension: c:\...\testfile.jszip
It seems other file types are not supported: https://nodejs.org/api/esm.html#esm_import_statements
What worked for my case is getting the normal require and using that. So I'm importing .graphql files using:
import {createRequire} from 'module';
const require = createRequire(import.meta.url);
require('graphql-import-node/register');
const myQuery = require('./myquery.graphql');
The graphql-import-node package does a require.extension[] = behind the scenes:
require.extensions['.graphql'] = loadPlainFile
But this is starting to become madness. You are probably better off using Webpack or something.
In this tutorial, how does npm start find the src/index/js to star the render? I can't find the configuration of this anywhere.
you can run npm run eject so that the project turn back to a normal webpack project. then you can find the configs.
If you look at package.json, the start script is defined there:
"scripts": {
"start": "react-scripts start",
It runs react-scripts start. And the package.json file for react-scripts looks like this:
"bin": {
"react-scripts": "./bin/react-scripts.js"
},
So we should see what does ./bin/react-scripts.js start do, which runs this code:
// #remove-on-eject-begin
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
// #remove-on-eject-end
'use strict';
// Do this as the first thing so that any code reading it knows the right env.
process.env.BABEL_ENV = 'development';
process.env.NODE_ENV = 'development';
// Makes the script crash on unhandled rejections instead of silently
// ignoring them. In the future, promise rejections that are not handled will
// terminate the Node.js process with a non-zero exit code.
process.on('unhandledRejection', err => {
throw err;
});
// Ensure environment variables are read.
require('../config/env');
const fs = require('fs');
const chalk = require('react-dev-utils/chalk');
const webpack = require('webpack');
const WebpackDevServer = require('webpack-dev-server');
const clearConsole = require('react-dev-utils/clearConsole');
const checkRequiredFiles = require('react-dev-utils/checkRequiredFiles');
const {
choosePort,
createCompiler,
prepareProxy,
prepareUrls,
} = require('react-dev-utils/WebpackDevServerUtils');
const openBrowser = require('react-dev-utils/openBrowser');
const semver = require('semver');
const paths = require('../config/paths');
const configFactory = require('../config/webpack.config');
const createDevServerConfig = require('../config/webpackDevServer.config');
const getClientEnvironment = require('../config/env');
const react = require(require.resolve('react', { paths: [paths.appPath] }));
const env = getClientEnvironment(paths.publicUrlOrPath.slice(0, -1));
const useYarn = fs.existsSync(paths.yarnLockFile);
const isInteractive = process.stdout.isTTY;
// Warn and crash if required files are missing
if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) {
process.exit(1);
}
// Tools like Cloud9 rely on this.
const DEFAULT_PORT = parseInt(process.env.PORT, 10) || 3000;
const HOST = process.env.HOST || '0.0.0.0';
if (process.env.HOST) {
console.log(
chalk.cyan(
`Attempting to bind to HOST environment variable: ${chalk.yellow(
chalk.bold(process.env.HOST)
)}`
)
);
console.log(
`If this was unintentional, check that you haven't mistakenly set it in your shell.`
);
console.log(
`Learn more here: ${chalk.yellow('https://cra.link/advanced-config')}`
);
console.log();
}
// We require that you explicitly set browsers and do not fall back to
// browserslist defaults.
const { checkBrowsers } = require('react-dev-utils/browsersHelper');
checkBrowsers(paths.appPath, isInteractive)
.then(() => {
// We attempt to use the default port but if it is busy, we offer the user to
// run on a different port. `choosePort()` Promise resolves to the next free port.
return choosePort(HOST, DEFAULT_PORT);
})
.then(port => {
if (port == null) {
// We have not found a port.
return;
}
const config = configFactory('development');
const protocol = process.env.HTTPS === 'true' ? 'https' : 'http';
const appName = require(paths.appPackageJson).name;
const useTypeScript = fs.existsSync(paths.appTsConfig);
const urls = prepareUrls(
protocol,
HOST,
port,
paths.publicUrlOrPath.slice(0, -1)
);
// Create a webpack compiler that is configured with custom messages.
const compiler = createCompiler({
appName,
config,
urls,
useYarn,
useTypeScript,
webpack,
});
// Load proxy config
const proxySetting = require(paths.appPackageJson).proxy;
const proxyConfig = prepareProxy(
proxySetting,
paths.appPublic,
paths.publicUrlOrPath
);
// Serve webpack assets generated by the compiler over a web server.
const serverConfig = {
...createDevServerConfig(proxyConfig, urls.lanUrlForConfig),
host: HOST,
port,
};
const devServer = new WebpackDevServer(serverConfig, compiler);
// Launch WebpackDevServer.
devServer.startCallback(() => {
if (isInteractive) {
clearConsole();
}
if (env.raw.FAST_REFRESH && semver.lt(react.version, '16.10.0')) {
console.log(
chalk.yellow(
`Fast Refresh requires React 16.10 or higher. You are using React ${react.version}.`
)
);
}
console.log(chalk.cyan('Starting the development server...\n'));
openBrowser(urls.localUrlForBrowser);
});
['SIGINT', 'SIGTERM'].forEach(function (sig) {
process.on(sig, function () {
devServer.close();
process.exit();
});
});
if (process.env.CI !== 'true') {
// Gracefully exit when stdin ends
process.stdin.on('end', function () {
devServer.close();
process.exit();
});
}
})
.catch(err => {
if (err && err.message) {
console.log(err.message);
}
process.exit(1);
});
Which starts a Webpack server:
const devServer = new WebpackDevServer(serverConfig, compiler);
// Launch WebpackDevServer.
devServer.startCallback(() => {
and then opens the browser:
openBrowser(urls.localUrlForBrowser);
while running npm run eject, you can find a config folder with all configuration files. Inside path.js file you can find the default path and if want you can change the default path there. Be careful while doing this since it is an irreversible process
Ref :http://blog.teamtreehouse.com/getting-started-create-react-app-tool