I'm facing some weird behavior when runing npm pack using the child_process.exec method.
const { exec } = require('child_process');
function execCommand( command ) {
exec(
command,
( err, stdout, stderr ) => {
if ( err != null ) {
throw err;
}
console.log( 'stdout -> ', stdout );
console.log( 'stderr -> ', stderr );
}
);
}
function packProject( projectName ) {
console.log('Packing Project');
const distDir = `dist/${projectName}`;
execCommand('cd "'+distDir+'" && npm pack', {
encoding: 'utf8'
});
}
packProject('test-app')
It does execute both commands as expected, but then it doesn't terminate the process after running npm pack.
Packing Project
stdout ->
stderr ->
stdout ->
stderr ->
stdout ->
stderr ->
I'm not getting any errors nor warnings during the process. Only after pressing Ctrl+C. But I suppose it's only because the process was manually terminated.
^Cnpm ERR! code ELIFECYCLE
npm ERR! errno 3221225786
Related
const { spawn } = require('child_process');
const fs = require('fs');
const path = require('path');
const root = __dirname;
function createSpawn(command, next) {
const child = spawn(command, {
stdio: 'inherit',
shell: true,
cwd: root,
});
child.on('exit', function () {
if (typeof next === 'function') {
next();
}
});
}
function install() {
fs.rmSync(path.resolve(root, '.husky'), {
recursive: true,
force: true,
});
createSpawn('npx husky install', () => {
createSpawn('npx husky add .husky/pre-commit "npm run pre-commit"', () => {
createSpawn('npx husky add .husky/commit-msg "npx --no -- commitlint --edit #EE#"', () => {
const file = path.resolve(root, '.husky/commit-msg');
let content = fs.readFileSync(file).toString();
content = content.replace('#EE#', '"$1"');
fs.writeFileSync(file, content);
});
});
});
}
install();
I test on windows, and it work fine
I used the yarn command to install dependencies, but an error occurred. It was still good before. I suspect that the permissions of the husky file are incorrect, but an error is reported in the yarn script
but when i use the commnad node install.js it work fine!!!
here is the error
yarn install v1.22.19
[1/4] 🔍 Resolving packages...
success Already up-to-date.
$ node install.js
node:internal/fs/utils:344
throw err;
^
Error: ENOENT: no such file or directory, open '/Users/ao/Desktop/Yeastar/PPV3/ppfe/.husky/commit-msg'
at Object.openSync (node:fs:585:3)
at Object.readFileSync (node:fs:453:35)
at /Users/ao/Desktop/Yeastar/PPV3/ppfe/install.js:32:34
at ChildProcess.<anonymous> (/Users/ao/Desktop/Yeastar/PPV3/ppfe/install.js:17:13)
at ChildProcess.emit (node:events:526:28)
at Process.ChildProcess._handle.onexit (node:internal/child_process:291:12) {
errno: -2,
syscall: 'open',
code: 'ENOENT',
path: '/Users/ao/Desktop/Yeastar/PPV3/ppfe/.husky/commit-msg'
}
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/install for documentation about this command.
I'm trying to commit and push changes using node without using any external npm packages
const { spawn,exec } = require('child_process');
const fs = require('fs');
const { stderr } = require('process');
(async ()=>{
if(fs.existsSync('./repo_dir'))
fs.rmSync('./repo_dir',{recursive:true});
exec(`git config --global --replace-all user.name "NAMEHERE" && git config --global --replace-all user.email "EMAIL#gmail.com" && git config --list`,(err,stdout,stderr)=>{
if(err)
console.log(`error: ${err}`);
if(stderr)
console.log(`stderr: ${stderr}`);
console.log(`stdout: ${stdout}`);
let git_spawn=spawn(`git`,[`clone`,`https://username:token#github.com/username/repo_dir.git`]);
git_spawn.stdout.on("data", data => {
console.log(`cloning stdout: ${data}`);
});
git_spawn.stderr.on("data", data => {
console.log(`cloning stderr: ${data}`);
});
git_spawn.on('error', (error) => {
console.log(`cloning error: ${error.message}`);
});
git_spawn.on("close", code => {
console.log(`child process exited with code ${code}`);
exec(`cd ./git_repo && touch blank.js && git add -A && git commit -m "updating" && git push && cd ..`,(err,stdout,stderr)=>{ //error somewhere here
console.log(`pushing error: ${err}`);
console.log(`pushing stdout: ${stdout}`);
console.log(`pushing stderr: ${stderr}`);
});
});
})
})();
but for some reason it doesn't work and I can't even pin point the error
output:
stdout: cloning stderr: Cloning into 'repo_dir'...
child process exited with code 0 pushing error: Error: Command failed:
cd ./repo_dir && touch blank.js && git add -A && git commit -m
"updating" && git push && cd ..
pushing stdout: On branch main Your branch is up to date with
'origin/main'.
nothing to commit, working tree clean
pushing stderr:
I'm guessing the problem is somewhere in committing and pushing
Creating an endpoint which respond with array of classifications based several ML models based on NaturalJS. I have two questions:
how to resolve this err,
how to force it to be sync.
The err and console.log:
Example app listening at http://localhost:3000
./src/data/
[ './src/data/trained.json', './src/data/untrained.json' ]
./src/data/trained.json
./src/data/untrained.json
[]
/Users/xyz/Desktop/Classifier/classifai-master/node_modules/apparatus/lib/apparatus/classifier/logistic_regression_classifier.js:178
classifier.__proto__ = LogisticRegressionClassifier.prototype;
^
TypeError: Cannot set property '__proto__' of undefined
at Function.restore (/Users/xyz/Desktop/Classifier/classifai-master/node_modules/apparatus/lib/apparatus/classifier/logistic_regression_classifier.js:178:26)
at restore (/Users/xyz/Desktop/Classifier/classifai-master/node_modules/natural/lib/natural/classifiers/logistic_regression_classifier.js:36:67)
at /Users/xyz/Desktop/Classifier/classifai-master/node_modules/natural/lib/natural/classifiers/logistic_regression_classifier.js:47:27
at /Users/xyz/Desktop/Classifier/classifai-master/node_modules/natural/lib/natural/classifiers/classifier.js:436:13
at FSReqCallback.readFileAfterClose [as oncomplete] (internal/fs/read_file_context.js:63:3)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! compoclassi#1.0.0 start: `node ./src/server.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the compoclassi#1.0.0 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! /Users/zyx/.npm/_logs/2021-01-08T12_02_36_696Z-debug.log
Please also see the code endpoint,
app.post('/suggest', urlencodedParser, (req, res) => {
if (req.body.description) {
var classifications = [];
const modelsPaths = readDirectory('./src/data/')
console.log(modelsPaths)
modelsPaths.forEach(modelsPath => {
console.log(modelsPath)
natural.LogisticRegressionClassifier.load(modelsPath, null, function (err, classifier) {
if (err) {
console.log(err)
} else {
var classification = {};
classification['path'] = modelsPath;
classification['classification'] = classifier.classify(req.body.description);
classifications.push(classification);
console.log(classifications)
}
})
})
console.log(classifications)
} else {
res.render('./pages/main')
}
})
And below the readDirectory() function: (but this seems work fine)
function readDirectory(directory) {
console.log(directory)
const tree = dirTree(directory);
var paths = [];
tree.children.forEach(child => {
paths.push('./'+child.path);
})
return paths;
}
This issue occurred because the second file contains internal format issue (not validated JSON)
I am trying to deploy my code but I am getting error
My index code is:
'use strict'
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendNotification =
functions.database.ref('/Notifications/{receiver_user_id}/{notification_id}')
.onWrite((data, context) =>
{
const receiver_user_id = context.params.receiver_user_id;
const notification_id = context.params.notification_id;
console.log('We have a notification to send to :' , receiver_user_id);
if (!data.after.val())
{
console.log('A notification has been deleted :' , notification_id);
return null;
}
const DeviceToken = admin.database().ref(`/Users/${receiver_user_id}/device_token`).once('value');
return DeviceToken.then(result =>
{
const token_id = result.val();
const payload =
{
notification:
{
title: "New Chat Request",
body: `you have a new Chat Request, Please Check.`,
icon: "default"
}
};
return admin.messaging().sendToDevice(token_id, payload)
.then(response =>
{
console.log('This was a notification feature.');
});
});
});
Error shown is this:
npm ERR! code ELIFECYCLE npm ERR! errno 1
npm ERR! functions# lint: `eslint .`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the functions# lint script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\Admin\AppData\Roaming\npm-cache\_logs\2020-06-02T11_48_47_185Z-debug.log
events.js:287
throw er; // Unhandled 'error' event
^
}
Error: functions predeploy error: Command terminated with non-zero exit code1
The error shown in C:\Users\Admin\AppData\Roaming\npm-cache_logs\2020-06-02T11_48_47_185Z-debug.log :
error code ELIFECYCLE
error errno 1
error functions# lint: `eslint .`
error Exit status 1
error Failed at the functions# lint script.
error This is probably not a problem with npm. There is likely additional logging output above.
verbose exit [ 1, true ]
You need the catch the error here:
then(response =>
{
console.log('This was a notification feature.');
}).catch(error => handle error here)
My mongodb database has two collections notes which holds each note and notebook which has a title and an array of notes containing an array of ids pointing to the note in the notes collection.
//notes:
{
"_id" : ObjectId("542afaaa4898f4042312872b"),
"title" : "Hello Universe",
"content" : "Saving to database"
}
//notebook
{
"_id" : ObjectId("53d0c6d8daeac43cf8412945"),
"title" : "My Notebook",
"notes" : [
ObjectId("53d0ca2fdaeac43cf8412946"),
ObjectId("542afe34a25e3c44160e6b05"),
ObjectId("542b7908a459766020342eae"),
ObjectId("542b79efa459766020342eaf"),
ObjectId("542b7a5ba459766020342eb0"),
ObjectId("542b7aa3d3b135c022b674ff"),
ObjectId("542bb47aa4ff29c820c22fdc"),
ObjectId("542bb720a4ff29c820c22fdd"),
ObjectId("542bddd5712c0dc426d41341"),
ObjectId("542bdec5712c0dc426d41342")
]
}
I use these to retrieve data to render this jade view.This is the code for my route:
router.get('/main',function(req,res){
var db=req.db;
var notebookCollection=db.get('notebook');
var notesCollection=db.get('notes');
var locals={};
locals.title="TakeNote:An easy to use note taking app for web and hopefully mobile";
locals.sidebar={};
locals.sidebar.items=[];
//get data for the first notebook and display it by default
locals.notebook={};
locals.notebook.notes=[];
notebookCollection.find({},{},function(err,docs){
if(err)
console.error(err);
else
{
console.log("Retrieving notebooks");
var noteIds;
if(docs.length)
{
console.log(docs)
for(var i=0;i<docs.length;i++)
{
locals.sidebar.items.push(docs[i].title);
locals.notebook.title=docs[i].title;
noteIds=docs[i].notes;
for(var j=0;j<noteIds.length;j++)
{
notesCollection.findOne({_id:noteIds[j]},function(err,doc){
if(err)
console.error(err);
else
{
locals.notebook.notes.push(doc);
//res.render('main',locals);
}
});
//putting it here might mean that it renders without any of the notes
//putting it here with a condition fails
/*
if(j===noteIds.length-1)
res.render('main',locals);
*/
}
}
//putting it here means it renders without any of the notes
}
}
});
});
Where can I call res.render('main',locals) so that it renders the template with all my data here?
EDIT Error when using async:
I get this error when using the async library:
E:\Do\hello_express\node_notes\node_modules\async\lib\async.js:641
tasks[index].apply(null, arguments);
^
TypeError: Object #<Promise> has no method 'apply'
at fn (E:\Do\hello_express\node_notes\node_modules\async\lib\async.js:641:34
)
at Object._onImmediate (E:\Do\hello_express\node_notes\node_modules\async\li
b\async.js:557:34)
at processImmediate [as _immediateCallback] (timers.js:336:15)
\
npm ERR! node_notes#0.0.1 start: `node ./bin/www`
npm ERR! Exit status 8
npm ERR!
npm ERR! Failed at the node_notes#0.0.1 start script.
npm ERR! This is most likely a problem with the node_notes package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR! node ./bin/www
npm ERR! You can get their info via:
npm ERR! npm owner ls node_notes
npm ERR! There is likely additional logging output above.
npm ERR! System Windows_NT 6.1.7600
npm ERR! command "C:\\Program Files\\nodejs\\\\node.exe" "C:\\Program Files\\nod
ejs\\node_modules\\npm\\bin\\npm-cli.js" "start"
npm ERR! cwd E:\Do\hello_express\node_notes
npm ERR! node -v v0.10.29
npm ERR! npm -v 1.4.14
npm ERR! code ELIFECYCLE
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR! E:\Do\hello_express\node_notes\npm-debug.log
npm ERR! not ok code 0
This is my async code:
function getActiveNotes(doc)
{
var noteIds=doc.notes;
async.map(noteIds,function(_id){
notesCollection.findOne({_id:_id})
},function(err,docs){
if(err)
console.error(err);
else
{
if(docs)
locals.notebook.notes=docs;
}
});
}
function getAllNotebooks()
{
notebookCollection.find({},{},function(err,docs){
if(err)
console.error(err);
else
{
if(docs)
{
for(var i=0;i<docs.length;i++)
{
locals.sidebar.items.push(docs[i].title);
}
}
}
});
}
function activeNotesOp(){
async.waterfall([notebookCollection.findOne({isActive:true}),getActiveNotes]);
}
async.parallel([getAllNotebooks,activeNotesOp],function(err,results){
if(err)
console.error(err);
else
console.log(results);
});
On reflection parallel may not be what you need, but I think this is a useful skeleton for you.
var notebooksIdx = 0;
notebookCollection.find({},{},function(err,notebooks){
async.each(
notebooks,
, function(notebook, cb) {
notesCollection.find({_id: {$in: notebook.notes}}, function(err, notes) {
if (err)
return cb(err);
return locals.notebook[notebooksIdx++].notes = notes;
})
}
, function(err) {
if (err) throw err;
res.render(....)
}
});
});
I used lodash method forEach to obtain the title of each notebook to populate the locals.sidebar,I used lodash.filter(this returns an array,obtained the first item) to find the activeNotebook and retrieve all the notes from it using the $in operator to perform a query for all the notes contained by the notebook and populated locals.notebook.notes with that data:
notebookCollection.find({},{},function(err,notebooks){
if(err)
console.error(err);
else
{
_(notebooks).forEach(function(notebook){
locals.sidebar.items.push(notebook.title);
});
//console.log(locals.sidebar.items);
var activeNotebooks= _.filter(notebooks,function(notebook){
return notebook.isActive;
});
var notes=activeNotebooks[0].notes;
notesCollection.find({_id:{$in:notes}},function(err,docs){
if(err)
console.error(err);
else
{
if(docs.length)
{
locals.notebook.notes=docs;
console.dir(locals);
res.render('main',locals);
}
}
});
}
});