node.js fork function and passing arguments to child-process - node.js

I pass arguments when create chlid-processes
if (cluster.isMaster) {
for (var i = 0; i < os.cpus().length; i++) {
var new_worker_env = {};
new_worker_env["WORKER_NAME"] = "worker" + i;
var new_worker = cluster.fork(new_worker_env);
}
}
and then try to read it in childs:
if ( process.env["WORKER_NAME"] != undefined ) instance.name = process.env["WORKER_NAME"];
but this var isn't exist, why?
Node v0.8.8

Seems to work for me on Windows, Node.js version 0.8.8
var cluster = require('cluster'),
os = require('os');
if (cluster.isMaster) {
for (var i = 0; i < os.cpus().length; i++) {
var new_worker_env = {};
new_worker_env["WORKER_NAME"] = "worker" + i;
var new_worker = cluster.fork(new_worker_env);
}
} else {
console.log(process.env['WORKER_NAME']);
}
outputs:
worker0
worker1

Related

Error [ERR_REQUIRE_ESM]: require() of ES Module ...\angular\node_modules\globby\index.js from ...\angular\gulpfile.js not supported

My angular project was perfectly run but for some error I tried to reinstall Nodejs and npm and problems began. After that when I try to use command npm start in my angular project I faced this error:
Error [ERR_REQUIRE_ESM]: require() of ES Module D:...\angular\node_modules\globby\index.js from D:...\angular\gulpfile.js not supported.
Instead change the require of index.js in D:...\angular\gulpfile.js to a dynamic import() which is available in all CommonJS modules.
at Object. (D:...\angular\gulpfile.js:4:14)
at async Promise.all (index 0) {
code: 'ERR_REQUIRE_ESM'
}
I didn't know if this reinstalling was my source of problem so I tried to move to my old version of Nodejs and npm but problem is still there.
current version of Nodejs and npm on my system:
D:\...\angular>node -v
v17.7.0
D:\...\angular>npm -v
7.19.1
I've read lots of same questions but answers didn't work for me.
for example I tried to use this solution on my gulpfile.js
And here is my gulpfile.js file:
var gulp = require("gulp");
var path = require('path');
var merge = require("merge-stream");
var globby = require('globby');
var concat = require('gulp-concat');
var less = require('gulp-less');
var uglify = require('gulp-uglify');
var cleanCss = require('gulp-clean-css');
var bundleConfig = require(path.resolve(__dirname, 'bundles.json'));
var production = false;
var styleEntries = {};
var scriptEntries = {};
function processInputDefinition(input) {
var result = [];
for (var i = 0; i < input.length; i++) {
var url = input[i];
if (url.startsWith('!')) {
result.push('!' + path.resolve(__dirname, url.substring(1)));
} else {
result.push(path.resolve(__dirname, url));
}
}
return result;
}
function fillScriptBundles() {
// User defined bundles
for (var k = 0; k < bundleConfig.scripts.length; k++) {
var scriptBundle = bundleConfig.scripts[k];
scriptEntries[scriptBundle.output] = globby.sync(processInputDefinition(scriptBundle.input), {
noext: true
});
}
}
function fillStyleBundles() {
// User defined styles
for (var k = 0; k < bundleConfig.styles.length; k++) {
var styleBundle = bundleConfig.styles[k];
styleEntries[styleBundle.output] = globby.sync(processInputDefinition(styleBundle.input), {
noext: true
});
}
}
function getFileNameFromPath(path) {
return path.substring(path.lastIndexOf('/') + 1);
}
function getPathWithoutFileNameFromPath(path) {
return path.substring(0, path.lastIndexOf('/'));
}
function createScriptBundles() {
var tasks = [];
for (var script in scriptEntries) {
tasks.push(
createScriptBundle(script)
);
}
return tasks;
}
function createScriptBundle(script) {
var bundleName = getFileNameFromPath(script);
var bundlePath = getPathWithoutFileNameFromPath(script);
var stream = gulp.src(scriptEntries[script]);
if (production) {
stream = stream
.pipe(uglify());
}
return stream.pipe(concat(bundleName))
.pipe(gulp.dest(bundlePath));
}
function createStyleBundles() {
var tasks = [];
for (var style in styleEntries) {
tasks.push(
createStyleBundle(style)
);
}
return tasks;
}
function createStyleBundle(style) {
var bundleName = getFileNameFromPath(style);
var bundlePath = getPathWithoutFileNameFromPath(style);
var stream = gulp.src(styleEntries[style])
.pipe(less({
math: 'parens-division'
}));
if (production) {
stream = stream.pipe(cleanCss());
}
return stream
.pipe(concat(bundleName))
.pipe(gulp.dest(bundlePath));
}
function build() {
production = true;
fillScriptBundles();
fillStyleBundles();
var scriptTasks = createScriptBundles();
var styleTasks = createStyleBundles();
return merge(scriptTasks.concat(styleTasks));
}
function buildDev() {
fillScriptBundles();
fillStyleBundles();
var scriptTasks = createScriptBundles();
var styleTasks = createStyleBundles();
console.log("Dynamic bundles are being created.");
return merge(scriptTasks.concat(styleTasks));
}
exports.build = build;
exports.buildDev = buildDev;

Node.js for loop output only last item from JSON

The code below only output the last result, I don't get it. I check if the updateDate item contains 2020-05 both items does and I get only the last one. The loop is not looping :)
const briefing = [
{
"updateDate": "2020-05-05T00:00:00.0Z",
},
{
"updateDate": "2020-05-06T00:00:00.0Z",
},
{
"updateDate": "2020-05-13T00:00:00.0Z",
}
];
let date = new Date();
var formattedYearMonth = date.getFullYear() + '-' + ('0' + (date.getMonth()+1)).slice(-2) + '-';
for (var i = 0; i < briefing.length; i++) {
var jsonDate = briefing[i].updateDate;
if (jsonDate.includes(formattedYearMonth)) {
var response = JSON.stringify(briefing[i]);
}
}return response;
}
for (var i = 0; i < briefing.length; i++) {
var jsonDate = briefing[i].updateDate;
if (jsonDate.includes(formattedYearMonth)) {
var response = JSON.stringify(briefing[i]); // <==== THIS IS WHERE YOUR PROBLEM LIES
}
}return response;
The loop is actually looping :). But for every run of the loop, you are resetting the value of response.
--EDITED--
For the response to be an array, you need to modify your code as
let response = [];
for (var i = 0; i < briefing.length; i++) {
var jsonDate = briefing[i].updateDate;
if (jsonDate.includes(formattedYearMonth)) {
response.push(JSON.stringify(briefing[i]));
}
}
return response;

Accessing variables from my index.js in another file

I am trying to make a bit of code execute as if it was in the index.js of my nodejs app.
I have the following code:
index.js
var data = [];
function populateData(){
for(var i = 0; i < 100; i++){
data.push(i);
}
}
populateData();
require('./other.js')();
other.js
module.exports = function(){
console.log(data);
}
However, this tells me data is not defined. Is there any way to read the data variable like this?
I tried
require('./other.js').apply(null);
and
require('./other.js').apply(this);
However neither worked for me
Use another module for common variable.
common.js
module.exports = {
data: []
}
index.js
const common = require('./common');
const other = require('./other');
function populateData(){
for(var i = 0; i < 100; i++){
common.data.push(i);
}
}
populateData();
other.test();
other.js
const common = require("./common");
module.exports = {
test: function(){
console.log(common.data);
}
}
You can pass the data to the file like this
index.js
var data = [];
function populateData() {
for (var i = 0; i < 100; i++) {
data.push(i);
}
}
populateData();
require('./other.js')(data);
other.js
module.exports = function(data) {
console.log(data);
};

making node wait for db call to get completed

I just started writing node.js code.
I'm writing a code that extracts data from a pdf file, cleans it up and stores it in a database (using couchdb and accessing that using nano library).
The problem is that the calls are being made asynchronously... so the database get calls (i make some get calls to get a few affiliation files during the clean up) get completed only after the program runs resulting in variables being undefined. is there any way around this?
I've reproduced my code below
const fs = require('fs');
const os = require('os');
var couchDB = require('couch-db').CouchDB;
var pdf_table_extractor = require('pdf-table-extractor');
const filename = "PQ-PRI-0005-1806-01-0000_quoteSlipForLIBVIDGI1.pdf"
var nano = require('nano')('https://couchadmin:difficulttoguessmypassword#dbdev.perilwise.com');
var server = new couchDB('https://db.url.com');
server.auth("admin","admin");
var db = nano.db.use('pwfb');
var temp = [];
//New callView function
async function callView(){
try{
const doc = await view('liabilitymdm','pi');
for (var i =0; i<doc.rows.length;i++){
tmp.push(doc.rows[i]);
};
return doc;
} catch(e){
console.log(e);
};
};
function suc(result){
let ttmp = [];
console.log(result);
var pageTables = result.pageTables;
var firstPageTables = pageTables[0].tables;
ttmp = callView();
//this console log shows Promise { <pending> }
console.log(ttmp)
for (var k = 0; k < firstPageTables.length; k++) {
var temp = firstPageTables[k];
if (temp.length > 0) {
dump.push(temp);
}
}
// console.log(dump);
var insurer = filename.substr(37,8);
read_quote_slip(insurer,dump);
}
var read_quote_slip = (insurer,data) => {
console.log("read_quote_slip correctly entered");
var finOut = {};
if (insurer === "LIBVIDGI"){
finOut.insurer = insurer;
finOut.policyType = data[2][0].replace(/Quotation for/g,"");
finOut.natureOfWork = data[13][3];
let dedpos = indexGetter(data, "Deductible")[0];
finOut.deductible = data[dedpos+1][0];
let cov = indexGetter(data, "Coverage Territory and Jurisdiction")[0];
finOut.coverageTerritory = data[cov+1][0].replace(/Territory/g,"");
finOut.coverageJurisdiction = data[cov+2][0].replace(/Jurisdiction/g,"");
let ext = indexGetter(data,"Extensions")[0];
finOut.coverage = data[ext+1][0].split(/\r?\n/);
let majexc = indexGetter(data,"Major Exclusions")[0];
finOut.exclusions = data[majexc+1][0].split(/\r?\n/);
let prdtl = indexGetter(data,"Description")[0];
let prm = premiumcompute(data,prdtl,dedpos);
finOut.premium = prm;
finCleaned = libvidgi_cleaned(finOut);
// console.log(finCleaned);
}
}
var indexGetter = (words,toFind) => {
var finindex = [];
for (var i = 0; i < words.length; i++){
for (var j = 0; j < words[i].length; j++){
if(words[i][j].indexOf(toFind) >=0 ){
finindex.push(i);
}
}
}
return finindex;
}
var premiumcompute = (data, from, to) => {
let finprem = [];
let numbop = to - from - 2;
let incr = 0;
for (var i = from+2; i < to; i++){
let pr = {};
pr.option = incr+1;
pr.sumInsured = data[i][2].replace(/ /g,"");
pr.premium = data[i][data[i].length - 1].replace(/ /g,"");
finprem.push(pr);
incr +=1;
}
return finprem;
}
var libvidgi_cleaned = (finOut) => {
return finOut;
}
var fal = (result) => {
console.log(result);
console.log("there was an error");
}
var readPDFFile = function(filename){
//Decide which insurer from the filename
// console.log(filename);
console.log(filename.substr(37,8)+"Printed on line 38");
insurer = filename.substr(37,8)
pdf_table_extractor(filename, (result) => {suc(result)} , fal);
}
var libvidgi_data_extract = (data) => {
console.log(data);
let arr = data.pageTables.tables;
for (var i = 0; i <= arr.length; i++ ){
console.log(arr[i]);
}
}
readPDFFile(filename);
This answer assumes you are using Node.js > v7.6
Since db.view accepts a callback, and you wish to wait for it to finish, one solution will be to promisify it - meaning to turn it into a promise which can be awaited. You can use a library like Bluebird or you can even use Node's builtin promisify util. Then you can rewrite callViews:
const {promisify} = require('util');
const view = promisify(db.view);
async function callView() {
try {
const doc = await view('liabilitymdm', 'pi');
// the async operation is now guaranteed to be done
// (if there is an error it will be caught by the catch clause)
for (var i = 0; i < doc.rows.length; i++) {
temp.push(doc.rows[i]);
}
console.log(temp);
} catch (e) {
}
}
If you are not using Node.js > v7.6 (and cannot use async\await you can still utilize promises, by using their then method:
const {promisify} = require('util');
const view = promisify(db.view);
function callView() {
view('liabilitymdm', 'pi')
.then(doc => {
for (var i = 0; i < doc.rows.length; i++) {
temp.push(doc.rows[i]);
}
console.log(temp);
return temp;
})
.then(temp => {
console.log(temp);
})
.catch(e => {});
}
Notice how the first then is returning something which is used in a later then.
To make Node run asynchronously, you can use the keywords async and await.
They work like this:
async function doSomething () {
const formattedData = formatData();
const result = await db.postToDatabase(formattedData);
// the below will not happen until the above line is finished
doSomethingElse(result);
}
It's pretty simple in Node to get functions to execute asynchronously. Just put the async keyword at the beginning of the function definition and then put await in front of anything that you want to block execution until completed.

node js function.then in not a function using q

Hello its so wired i am trying to do async function but when i use it i get error
using q
on package json
"q": "^1.4.1"
TypeError: helper.setNextUserNewsAction(...).then is not a function
this is my helper
module.exports = function() {
return {
setNextUserNewsAction: setNextUserNewsAction
}
}();
function setNextUserNewsAction(minutesToSet){
var defer = q.defer();
var x = minutesToSet;
var d = new Date();
var nextNews = new Date(d.getTime() + x*60000);
var minutes = nextNews.getMinutes();
var newMinutesToSet = 0;
for (var i = 0 , j = minutesToSet; j <= 60; i+=minutesToSet,j+=minutesToSet) {
if (minutes > i && minutes < j)
return newMinutesToSet = (i % 60);
}
nextNews.setMinutes(newMinutesToSet);
nextNews.setSeconds(00);
var NextNewsAction = {
AccessDate: nextNews,
Type: 'News',
Current: 1
}
defer.resolve(NextNewsAction);
return defer.promise;
}
and when i call this function in my controller it send me that error
var helper = require('../helpers/playlist');
helper.setNextUserNewsAction(15).then(function(action){
console.log(action);
},function(err){
console.log(err);
});
i have also try doing that with try and catch and still same error
well its not the first time or the 20 i am using q
hope somebody can help
The problem is that you are returning something from the for loop:
for (var i = 0, j = minutesToSet; j <= 60; i += minutesToSet, j += minutesToSet) {
if (minutes > i && minutes < j)
return newMinutesToSet = (i % 60);
}
So the setNextUserNewsAction function is not returning a promise, therefore there is no .then().
Try this:
var q = require('q');
module.exports = function() {
return {
setNextUserNewsAction: setNextUserNewsAction
}
}();
function setNextUserNewsAction(minutesToSet){
var defer = q.defer();
var x = minutesToSet;
var d = new Date();
var nextNews = new Date(d.getTime() + x*60000);
var minutes = nextNews.getMinutes();
var newMinutesToSet = 0;
for (var i = 0, j = minutesToSet; j <= 60; i += minutesToSet, j += minutesToSet) {
if (minutes > i && minutes < j) {
newMinutesToSet = (i % 60);
}
}
nextNews.setMinutes(newMinutesToSet);
nextNews.setSeconds(00);
var NextNewsAction = {
AccessDate: nextNews,
Type: 'News',
Current: 1
}
defer.resolve();
return defer.promise;
}

Resources