module not found importing function of npm script - javascript

//something.spec.js
import { myCustomGlob } from './scripts/index'
describe.only('generate index', () => {
console.log(myCustomGlob) //MODULE NOT FONUD ERROR
})
//script
const fs = require('fs')
const myCustomGlob = () => {
//some fs operation
}
export {
myCustomGlob
}
I have a npm script that used glob and fs to generate some code to create a new file. But I want to write unit test for those function too, but I got MODULE 'fs' NOT FOUND error. why? I thought 'fs' is included since I import myCustomGlob?

Try import * as fs from 'fs' or just try removing the quotes from the first fs. You are looking up the module with a string, that doesn't work.

Related

SSR with React : Unexpected token '<' in call to renderToString()

I'm working on SSR with react but I'm encountering the following error.
Syntax error: Unexpected token '<'`
<div id="root">${ReactDOMServer.renderToString(<App />)}</div>```
^
As mentioned is here
babel-register doesn't process the file it is called from.
Therefore, I rightly declared my babel dependencies in a new file, however I'm still getting the above error.
Below is my index.js file
import babelRegister from '#babel/register';
import ignoreStyles from 'ignore-styles';
babelRegister({
ignore: [/node_modules/],
presets: ['#babel/preset-env', '#babel/preset-react'],
});
import express from 'express';
import appRender from './server.js';
const app = express();
appRender(app);
My server.js file.
import initialRenderRoutes from './routes/initialRenderRoutes.js';
import path from 'path';
const appRender = (app) => {
const __dirname = path.resolve();
app.use(express.static(path.resolve(__dirname, '../build')));
app.use('*', initialRenderRoutes);
const port = 5000;
app.listen(port, () => console.log(`Server running on port ${port}`));
};
export default appRender;
My initialController.js file
import fs from 'fs';
import ReactDOMServer from 'react-dom/server.js';
import path from 'path';
import App from '../../src/App.js';
const initialRenderController = (req, res, next) => {
console.log(path.resolve());
fs.readFile(
path.resolve('../client/build/index.html'),
'utf8',
(err, data) => {
if (err) {
console.log(err);
return res.status(500).send('Internal Server Error');
}
return res.send(
data.replace(
'<div id="root"></div>',
`<div id="root">${ReactDOMServer.renderToString(<App />)}</div>`
<<<<The problem lies here>>>>
)
);
}
);
};
export default initialRenderController;
Is it something related to babel, please help.
Try the below changes in your index.js file,
require('ignore-styles');
require('#babel/register')({
ignore: [/(node_modules)/],
presets: ['#babel/preset-env', '#babel/preset-react']
});
require('./server');
require('./initialController');
The above should work, I tested locally the below, it works perfectly fine.
My server.js
import express from 'express';
import fs from 'fs';
import path from 'path';
import React from 'react';
import ReactDOMServer from 'react-dom/server';
import App from '../App';
const app = express();
app.use('^/$', (req, res, next) => {
fs.readFile(path.resolve('./build/index.html'), 'utf-8', (err, data) => {
if (err) {
console.log(err);
return res.status(500).send("Some error occurred")
}
return res.send(data.replace('<div id="root"></div>', `<div id="root">${ReactDOMServer.renderToString(<App />)}</div>`))
})
});
app.use(express.static(path.resolve(__dirname, "..", "build")));
app.listen(5000, ()=>{
console.log("App running on port 5k")
})
index.js
require('ignore-styles');
require('#babel/register')({
ignore: [/(node_modules)/],
presets: ['#babel/preset-env', '#babel/preset-react']
});
require('./server');
I hope you have the .babelrc file with the required presets.
Update in response to comment:
Consider removing type: "module", since it will throw error when you use require. #babel/register will run files using babel on the fly. The require hook will bind itself to the node’s require and will automatically compile files at runtime. server.js using es module won't clash if you remove type: "module". The order of require matters, we require babel-register in index.js with the presets needed to recognize the syntaxes in the then-required server.js.
I believe there are two things that need to be changed. One on your initialControler.js you are using export default in a node.js file, use module.exports
module.exports vs. export default in Node.js and ES6
You should change all the imports in your node files.
You use export / export default in React and then import to pull in the files
https://www.geeksforgeeks.org/reactjs-importing-exporting/
module.exports and require to pull in the files for Node
What is the purpose of Node.js module.exports and how do you use it?
Second they moved the app.get into that renderReact.js file and then required it into their index.js file. However on your server.js file I don't see you importing in your initialController file.
From your example it looks like you should be doing something like this:
Server.js
let initialController = require('/path to this file');
initialController(app)
Yow broh don’t waste yow time reading them parchments.
All you need to do is remove any space b4 and after each ><
const val= ReactDOMServer.renderToString(<App />);
/// make sure you don’t have any sort of space
/// between them > < and yow ${}
/// is better if you store that long text into an small var, as I did to ///prevent prettier or some other 💩 to add a line break of an space
return res.send( `<div id="root">${val}</div>`);

Python script not executing pickle.load when called from nodejs app

I have an nodejs app which calls python script from a controller. Scripts run fine when I run from terminal directly and works fine as well when called from node app but it only stucks on this specific line model = pickle.load(open("model.pkl", "rb")). Any help would be appreciated.
predict.py
import sys
import json
import pickle
import os
def get_size(weight, height, age):
model = pickle.load(open("model.pkl", "rb"))
return model.predict([[height,weight,age,bmi]])[0]
calculated_size = get_size(69,167,26)
print(calculated_size)
sys.stdout.flush()
results.js
const scriptPath = path.dirname(require.main.filename) + '/python-scripts/predict.py';
const pythonProcess = spawn('python', [ scriptPath, 'user_inputs', JSON.stringify(results) ], {cwd: path.dirname(require.main.filename)+'/python-scripts'});
pythonProcess.stdout.on('data', async (data) => {
console.log(data.toString());
})
Fixed by changing python version in spawn:
const pythonProcess = spawn('python3', [ scriptPath, 'user_inputs', JSON.stringify(results) ], {cwd: path.dirname(require.main.filename)+'/python-scripts'});

Load local dll with node-ffi: No such file

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.

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!!!

Categories