I have a files.js file and am requiring it at the start of my code.
When I use:
const files = require('./lib/files');
I get this error:
Error: Cannot find module './lib/files'
However if I test it with another one of the files in the same folder like:
const files = require('./lib/repo');
It runs.
files.js:
const fs = require('fs');
const path = require('path');
module.exports = {
getCurrentDirectoryBase: () => {
return path.basename(process.cwd());
},
directoryExists: (filePath) => {
return fs.existsSync(filePath);
}
};
I would use tree command however I have too many node modules installed to show it correctly so:
const { getCurrentDirectoryBase, directoryExists } = require('./lib/files')
Related
I am using webpack 5.12.3 for bundle split.
He is my webpack.config.js
const { resolve } = require('path')
const webpack = require('webpack')
const TerserPlugin = require('terser-webpack-plugin')
const ProgressBarPlugin = require('progress-bar-webpack-plugin')
const { getIfUtils, removeEmpty } = require('webpack-config-utils')
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const CompressionPlugin = require("compression-webpack-plugin");
module.exports = env => {
const { ifProduction, ifNotProduction } = getIfUtils(env)
const mode = ifProduction('production', 'development')
return {
mode,
//context: resolve('./src/public/js'),
entry: {
index: './.dist/public/main.js',
},
output: {
filename: '[name].min.js',
chunkFilename: '[name].min.js',
path: resolve('./src/public/js/'),
pathinfo: true,
},
}
remaining code contains rules,optimzations,minimizers etc.
Here is main.js which is used in webpack config entry
import 'babel-polyfill';
var Routes = require('../routes/react.jsx');
var Client = require('react-engine/lib/client');
// Include all view files. Browerify doesn't do
// this automatically as it can only operate on
// static require statements.
// Not required as part for webpack.
//require('./views/**/*.jsx', {glob: true});
// boot options
var options = {
routes: Routes,
// supply a function that can be called
// to resolve the file that was rendered.
viewResolver: function viewResolver(viewName) {
return require('./views/' + viewName);
}
};
document.addEventListener('DOMContentLoaded', function onLoad() {
console.log(typeof(options));
console.log(options);
Client.boot(options);
});
Here for all pages in application this code is getting executed only one bundle file is created. My aim is to have separate bundle for every page in /src/views . I did try to get viewName from viewResolver its not getting executed . Can anyone please suggest me how should I change code so that I can have entry for every page (that is possible using entry section of webpack config) but as everything is coming to main.js . If I try to add another main1.js what should be its code and how execution should come there ?
I have many different modules in a project, each module has it's own folder, within each module, there are 3 files:
index.js
index.test.js
data.js
Every module has these files, same file names and different content.
For the index.test.js files, the import statements are all the same for all index.test.js files in all modules, look like this:
const runAnalysis = require('./index');
const { data } = require('./data');
const { formatData } = require('utils');
const formattedData = formatData(data);
Since these import statements are the same for all index.test.js files, is there a way to consolidate these into one line, so it doesn't have to be repeated over and over in every module?
Is there a way to put these import statements in a header file, and then each index.test.js can just import the header file?
Not sure if this is efficient or recommended, but it works.
Create a util js file and it can live at the project root directory, let's name it import-util.js with the following code.
const { formatData } = require('utils');
const getMyImports = (dirname) => {
const runAnalysis = require(`${dirname}/index`);
const { data } = require(`${dirname}/data`);
const formattedData = formatData(data);
return {
runAnalysis,
formattedData
}
};
exports.getMyImports = getMyImports;
Then this file can be used like this to get the runAnalysis and formattedData
const { runAnalysis, formattedData } = require('../import-util').getMyImports(__dirname);
__dirname is the trick to make it work, it provides the directory path for the index.js and data.js to be imported.
This single line can now be used in every module folder, given the folder contains the index.js and data.js, it works the same as the following 4 lines of code.
const runAnalysis = require('./index');
const { data } = require('./data');
const { formatData } = require('utils');
const formattedData = formatData(data);
I need to find a way to get the newest folder created in a directory. Usually there are 3-5 different folders inside of a folder, and I want to find the newest one either by folder name (newest version numbering) or date and time created. Generally the folder name would like like this:
version-0101xxxxxxxxxxxx
(x representing the newest version)
You can get directories with 'fs' using 'readdirSync', then look inside each directory recursively.
This code snippet is extracted from (this answered question):
const fs = require('fs');
const path = require('path');
function flatten(lists) {
return lists.reduce((a, b) => a.concat(b), []);
}
function getDirectories(srcpath) {
return fs.readdirSync(srcpath)
.map(file => path.join(srcpath, file))
.filter(path => fs.statSync(path).isDirectory());
}
function getDirectoriesRecursive(srcpath) {
return [srcpath, ...flatten(getDirectories(srcpath).map(getDirectoriesRecursive))];
}
let dirs = getDirectoriesRecursive(__dirname);
console.info(path);
This will get you an array with all directories, then you just need to loop your array with the condition you need.
You can use node.js built-in fs module for this. First of all you need to list all the files and folders in the directory that you intend to search.
let dirs = await fs.readdir(dirName, {
withFileTypes: true,
});
You can use fs.promises.readdir for this. Make sure to add the option "withFileTypes" because it gives additional information that you can use to distinguish folders from files.
You can then filter all files like this:
dirs = dirs.filter((file) => file.isDirectory()).map((dirent) => dirent.name);
This gives you a result like ["firstFolder", "secondFolder", etc]
And then you can loop through the above array and find the newest folder by using the fs.promises.stat method
let newestFolder = await fs.stat(path.join(dirName, dirs[0]));
let newestFolderName = dirs[0];
for (let directory of dirs) {
const stats = await fs.stat(path.join(dirName, directory));
if (stats.ctimeMs > newestFolder.ctimeMs) {
newestFolder = stats;
newestFolderName = directory;
}
}
And then you can create the absolute path of that directory using path module:
const absoultePath = path.resolve(path.join(dirName, newestFolderName));
Here is how the function looks using promises:
const fs = require("fs/promises");
const path = require("path");
async function getNewestDirectory(dirName) {
let dirs = await fs.readdir(dirName, {
withFileTypes: true,
});
dirs = dirs.filter((file) => file.isDirectory()).map((dirent) => dirent.name);
let newestFolder = await fs.stat(path.join(dirName, dirs[0]));
let newestFolderName = dirs[0];
for (let directory of dirs) {
const stats = await fs.stat(path.join(dirName, directory));
if (stats.ctimeMs > newestFolder.ctimeMs) {
newestFolder = stats;
newestFolderName = directory;
}
}
console.log("newestFolder", newestFolder);
console.log("newestFolderName", newestFolderName);
return path.resolve(path.join(dirName, newestFolderName));
}
and using synchronous approach(not recommended):
const fs = require("fs");
let dirs = fs.readdirSync(".", {
withFileTypes: true,
});
dirs = dirs.filter((file) => file.isDirectory()).map((dirent) => dirent.name);
let newestFolder = fs.statSync(dirs[0]);
let newestFolderName = dirs[0];
for (let directory of dirs) {
const stats = fs.statSync(directory);
if (stats.ctimeMs > newestFolder.ctimeMs) {
newestFolder = stats;
newestFolderName = directory;
}
console.log("newestFolder", newestFolder);
console.log("newestFolderName", newestFolderName);
}
Hello I am new to testing with mocha/chai/sinon and sequelize-test-helpers
Trying to use proxyquire to override the require but having issues
Getting this following error about the path:
Error: ENOENT: no such file or directory, scandir 'C:<local-directories-path>\ecommerce-pern-app\server\src\models'
I dont get why there is a src folder when I don't have a src folder at all I am using the proxyquire in the test file and its path is from the server directory would be:
server/specs/services/user-service.spec.js
"use strict";
const chai = require('chai');
const {match, stub, resetHistory, spy} = require('sinon');
const proxyquire = require('proxyquire');
const path = require('path');
const service = path.resolve('./services/userService.js')
var sinonChai = require("sinon-chai");
chai.should();
chai.use(sinonChai);
console.log(service)
const {makeMockModels, sequelize, dataTypes,} = require('sequelize-test-helpers');
describe('Idea Controller', function () {
const uid = '6a88e9b5-33a2-403f-ac3d-e86413ac101d'
const data = {
email: 'testface#test.com',
password: '123456',
is_admin: false,
first_name: 'Testy',
last_name: 'McTestface',
google_id: null,
facebook_id: null
}
describe('findAll()', function () {
it('Success case ', function () {
const mockResponse = () => {
const res = {};
res.json = stub().returns(res);
return res;
};
let res = mockResponse();
const User = {findAll: stub()};
const mockModels = makeMockModels({User});
Idea.findAll.resolves(data);
const UserService = proxyquire(service, {
"save": {}
});
UserService.findAll({}, res);
Idea.findAll.should.have.been.called; // passes
res.json.should.have.been.called; //fails
});
})
});
In the above code I am using the proxyquire like this:
const proxyquire = require('proxyquire');
const path = require('path');
const service = path.resolve('./services/userService.js')
const {makeMockModel} = require('sequelize-test-helpers');
const mockModels = makeMockModels({User});
const UserService = proxyquire(service, {
"../models": mockModels
});
As I am trying to use the path to find the server/service/userService.js file which is relatively located from the test file at ../../services/userService.js. I have got this bug that there is src folder there when I do not have a src directory at all even!
As the bug is saying:
Error: ENOENT: no such file or directory, scandir 'C:<local-directories-path>\ecommerce-pern-app\server\src\models'
Whatever I try about file path is not working I tried path.resolve, path.join and directly typing the path into it as like ../../services/userService.js
here is the
server/services/userService.js
const Models = require('../models');
const { User } = Models;
const save = async ({ id, ...data }) => {
const user = await User.findOne({ where: { uid: id } })
if (user) return await user.update(data)
return null
}
module.exports = save;
I just want the path to with proxyquire to work
What is this \src\models path from the error, I dont have a src/models path route at all!
This is a quote from sequelize-test-helpers's readme.
As a convenience, makeMockModels will automatically populate your mockModels with mocks of all of the models defined in your src/models folder (or if you have a .sequelizerc file it will look for the models-path in that). Simply override any of the specific models you need to do stuff with.
So you need to provide .sequelizerc file and define models-path.
So I'm planning to separate my functions into separate files and then import them into a single index.js which then becomes the main exporter. So I'm wondering if having something like var bcrypt = require('bcrypt') in several of my files be slower than just having it in one file.
Here's how I'm planning to group and export in index.js
const fs = require('fs');
const path = require('path')
const modules = {}
const files = fs.readdirSync(__dirname)
files.forEach(file => {
if (file === 'index.js') return
let temp = require(path.join(__dirname, file))
for (let key in temp) {
modules[key] = temp[key]
}
});
module.exports = modules
As an example of what I mean:
file1.js
var bcrypt = require("bcrypt");
module.exports.file1test = "hi"
file2.js
var bcrypt = require("bcrypt");
module.exports.file2test = "bye"
No, it does not. Whenever a module is required for the first time, the module's code runs, assigns something to its exports, and those exports are returned. Further requires of that module simply reference those exports again. The logic is similar to this:
const importModule = (() => {
const exports = {};
return (name) => {
if (!exports[name]) exports[name] = runModule(name);
return exports[name];
};
})();
So, multiple imports of the same module is no more expensive than referencing an object multiple times.