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,
Related
This is how I managed to be able to read the json file
posts.js file
const PATH = require('/Users/jorgesisco/Dropbox/Programming_Practice/Web_Development/PWJ/Module-8/Blog/pwj-module-8-my-blog-api/exercise/data.json');
class Post {
get() {
// get posts
}
getIndividualBlog() {
// get one blog post
}
addNewPost() {
// add new post
}
readData() {
return PATH;
}
}
module.exports = Post;
Now in app.js I call the function and I am able to see the json file in postman.
// 1st import express
const express = require('express');
const app = express();
const Post = require('./api/models/posts');
const postsData = new Post();
const posts = [
{
id: '1581461442206',
title: 'This is a New Blog Post',
content: 'This is the content! ',
post_image: 'uploads/post-image-1581461442199.jpg',
added_date: '1581461442206',
},
];
// const result = posts.flatMap(Object.values);
app.get('/api/posts', (req, res) => {
res.status(200).send(postsData.readData());//here I call the function to see json file in postman
});
app.listen(3000, () => console.log('listening on http://localhost:3000'));
I think I shouldn't use the whole file path for the json file but when I just use something like ./data.json an error happen because it can't find the json file.
For accessing the files from the same dir you need to pass './'
Example: require('./data.json');
for accessing the files from one dir out from current dir '../'
Example: require('../data.json');
For accessing the files from two dir out within different folder '../../foldername/data.json'
Example: require('../../dataFolder/data.json');
The file path is referenced from the directory where you run the main code (app.js)
Move your data.json file inside the directory where your code is located. Let's say main_code/datadir. So, it looks like this now -
-- maincode
-- datadir
-- data.json
-- posts.js
-- app.js
Refer the file in posts.js code as require('./datadir/data.json')(Assuming datadir/ is in the same path/level as your app.js code)
Run app.js
I try to load a local .dll according the examples on stackoverflow and node-ffi documentation.
But I get the error ENOENT: no such file or directory, open '../test/user32.dll.so'. The file is there (no exception).
The extension '.so' is added automatically. Any idea what I'm doing wrong? Is this code plattform dependent? I'm on Debian.
const path = require('path');
const fs = require('fs');
const ffi = require('ffi');
function setCursor() {
const dllFile = path.join('../test', 'user32.dll');
if (!fs.existsSync(dllFile)) {
throw (new Error('dll does not exist'));
}
const user32 = ffi.Library(dllFile, {
"SetCursorPos": [
"bool", ["int32", "int32"]
]
});
console.log(user32.SetCursorPos(0, 0));
}
setCursor();
It looks like path doesn't recognize ../test as being the parent folder. I think path.join(__dirname, '..', 'test', 'user32.dll'); should get you to the right place.
I'm using Node.js to build a web application.
I have two files. Server.js - where I call the server to go online etc. And the other one is a file which includes a big object with data. I imported the file with data into server.js, I get the object in postman when I set the website to be live. But I can't dive inside the object to get the data inside the object. The error I'm getting says that the variable where my data is stored is not defined.
I think the fix is to import albumsData variable into server.js, but im completely stuck and can't find how to do it. If anyone has any idea, please share.
albumsData.js
const express = require('express');
const router = express.Router();
let albumsData = {
filled with data
}
router.get('/albumData', (req, res) => {
res.send(albumsData);
});
module.exports = router;
Server.js
app.use(require('./api/albumData/unikkatilData'))
app.use((req, res) => {
res.status(404)
.send(albumsData)
});
app.listen(4000, () => {
console.log('hello worldd')
})
If you want the albumsData object then you can do it like this:
In you albumsData.js file:
const albumsData = {
// Bunch of data
}
module.exports = albumsData
Then in your server.js file:
const albumData = require('./api/albumsData') // Make sure this path points directly to the albumsData.js file
move enter code here to new file (ex utils.js)
and export it exports.albumsData = albumsData; then you can call it
with const utils = require('./utils') ; utils.albumsData
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!!!
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));
});