Can I export modules from FS? - javascript

In my models folder I have a lot of files like ..
// Account.js
module.exports = mongoose.model('Account', AccountSchema)
...
// Rules.js
module.exports = mongoose.model('Rules', RulesSchema)
And in my index.js file (same folder ./models).
The reason is to lookup all files in ./models folder, and export as named export
// index.js
const mathJSFiles = /^[^index].*\.js$/gmi;
fs.readdirSync('.')
.filter(file => file.search(mathJSFiles) >= 0)
.forEach(file => {
file = path.basename(file, '.js')
exports[file] = require(join(models, file))
})
So in another file main.js I want to do like that...
import * as Models from './models'
Models.Account
Or
import { Account } from './models'
This is possible?

I would recommend doing something like the following:
// main.js
var glob = require('glob')
, path = require('path');
glob.sync('./models/**/*.js').forEach( function( file ) {
require(path.resolve(file));
});

Related

directory is not creating

Am trying to create a directory with subfolders in my application. The new request will create folders only if the parent folder is already there but not creating if root folder is not there.
import { mkdir } from 'fs';
mkdir(join(__dirname, '../folder_to_create_directory/', req.body.path), (err) => {
if (err) {
return "error";
}
return "success"
});
The req.body.path is a path string eg: test/folder/subfolder. The code will work only if we create the "test" folder manually (it is not returning "success" message too even though the directory is being created). IF the test folder is not there then the directory is not creating.
expected output:-
folder_to_create_directory/test/folder/subfolder
You can use fs library to work with a file system.
For nested dirs:
var fs = require('fs');
var dir = join(__dirname, '../folder_to_create_directory/', req.body.path);
if (!fs.existsSync(dir)){
fs.mkdirSync(dir, { recursive: true });
}
Or, for individual dirs:
var fs = require('fs');
var dir = join(__dirname, '../folder_to_create_directory/', req.body.path);
if (!fs.existsSync(dir)){
fs.mkdirSync(dir);
}
you are missing an option "{recursive: true}". Try this example:
const { mkdir } = require("fs");
const {join} = require('path')
const path = join(__dirname, "../folder_to_create_directory", 'test/folder/subfolder')
mkdir(path, { recursive: true }, (err) => {
if (err) {
return "error";
}
return "success";
});

How to apply a function from node package to all the files in a directory?

I've installed mammoth.js module which converts docx to html. I can use it with a single file.
How do I use the same module for all the files in a specific folder? I'm trying to save an output html files while keeping the original name (not the extension, of course). Probably I have to require some other packages...
The code below is for a single file from the desired directory:
var mammoth = require("mammoth");
mammoth.convertToHtml({path: "input/first.docx"}).then(function (resultObject) {
console.log('mammoth result', resultObject.value);
});
The system is win64
Something like this should work
const fs = require('fs')
const path = require('path')
const mammoth = require('mammoth')
fs.readdir('input/', (err, files) => {
files.forEach(file => {
if (path.extname(file) === '.docx') {
// If its a docx file
mammoth
.convertToHtml({ path: `input/${file}` })
.then(function(resultObject) {
// Now get the basename of the filename
const filename = path.basename(file)
// Replace output/ with where you want the file
fs.writeFile(`output/${filename}.html`, resultObject.value, function (err) {
if (err) return console.log(err);
});
})
}
})
})

require all model of mongoose in express app.js

In my app.js of express app, I always have to include model every time I created a model
require('./models/Users')
require('./models/Projects')
Is there a way to avoid this? something like require('./models/*) ?
using glob to get all file in models path
var glob = require( 'glob' )
, path = require( 'path' );
glob.sync( './models/**/*.js' ).forEach( function( file ) {
require( path.resolve( file ) );
});
Using native nodejs, You can read the directory and load/require modules dynamically.
const fs = require("fs");
const path = require("path");
const models = fs.readdirSync("./models/");
models.forEach((dir) => {
if (fs.statSync(dir).isFile) require(path.join("./models/", dir));
});
Util:
const getModels = (dir) => {
return fs
.readdirSync(dir)
.filter((file) => fs.statSync(file).isFile)
.map((file) => require(path.join("./models/", file)));
};
module.exports ={getModels}
// How to use
const models = getModels("./models/")
Create a Separate file which will include all the exported module file and just export on objects and use it whenever required,

env-vars in React using Dotenv and Webpack

I want to access some of my environment variables defined in the frontend (React).
I have the following setup:
React + NodeJS (I do NOT use create-react-app)
Webpack 4
Dotenv
I have tried to follow https://medium.com/#trekinbami/using-environment-variables-in-react-6b0a99d83cf5#0618 but it does not work either any error is thrown.
webpack.config.js
const dotenv = require("dotenv");
module.exports = () => {
// call dotenv and it will return an Object with a parsed key
const env = dotenv.config().parsed;
// reduce it to a nice object, the same as before
const envKeys = Object.keys(env).reduce((prev, next) => {
console.log(prev)
prev[`process.env.${next}`] = JSON.stringify(env[next]);
return prev;
}, {});
return {
...,
plugins: [
new webpack.DefinePlugin(envKeys)
],
...
}
With above Webpack config I think I should be able to do <h4>My var: {process.env.REACT_APP_MY_VAR}</h4> in file.js, of course I have defined REACT_APP_MY_VAR in my .env-file located in the project root.
With above I expect file.js to render the value of REACT_APP_MY_VAR, but i does render nothing, either the value or an error.
I would recommend using dotenv-webpack instead of dotenv package for easy configuration.
4 simple steps:-
1) install dotenv-wepack using
npm install dotenv-webpack --save
2) Create .env file at root of application
API_URL=http://localhost:8000
3) Add this to your webpack config file.
const Dotenv = require('dotenv-webpack');
module.exports = {
...
plugins: [
new Dotenv()
]
...
};
4) Use env variable inside your application anywhere.
import React from 'react';
const App = () => {
return (
<h1>{process.env.API_URL}</h1>
);
}
export default App;
Hope that helps!!!

Webpack require.context does not work with Path.resolve

webpack.config.js
"use strict";
const Path = require("path");
const resolvePath = (...paths) => Path.resolve(__dirname, ...paths);
module.exports = {
entry: {
data: "./src/data/index.ts" // resolvePath("src", "data", "index.ts") does not work
}
/** more **/
}
index.ts
const req = require.context("./yaml", true, /\.ya?ml$/i);
req.keys().forEach((key: any) => req(key));
Using "./src/data/index.ts" or resolvePath("src", "data", "index.ts") compile the code. But only "./src/data/index.ts" includes the YAML files. YAML files are located at ./src/data/yaml.
How does Path.resolve affect require.context? If I want to use Path.resolve, how should I write the correct require.context?

Categories