Node.js spawn ENOENT error - node.js

So I followed this answer and made it to the last step, correctly I think. But then what? I'm trying to run a node file, but it doesn't appear to be in the file listed at the PATH directory. How am I supposed to get it in that folder?
My node entry file:
'use strict';
var express = require("express");
var child_process = require("child_process");
var app = express();
app.get("/go", function(req, res, next) {
var stream = child_process.spawn("node file.js").on("error", function(error) {
console.log("Error!!! : " + error);
throw error;
});
});
app.get("/", function(req, res, next) {
console.log("Hit main page.");
res.end("Got me.");
});
app.listen( (process.env.PORT || 4000), function() {
console.log("Example app listening on Heroku port " + process.env.PORT + " or local port 4000!");
});
And file.js, the file I'm attempting to open:
'use strict';
function sayHello() {
console.log("Hello.");
}
sayHello();

In your spawn method, you should have:
app.get("/go", function(req, res, next) {
var stream = child_process.spawn("node", ["file.js"]).on("error", function(error) {
console.log("Error!!! : " + error);
throw error;
});
});

Related

Why am I not able to upload file with following nodeJS code

I am trying to learn to upload a file using the following code:
var express = require('express');
var app = express();
var fs = require("fs");
var bodyParser = require('body-parser');
var multer = require('multer');
app.use(express.static('public'));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(multer({dest:'./uploads/'}).single('file'));
app.get('/index.htm', function (req, res) {
res.sendFile( __dirname + "/" + "index.htm" );
})
app.post('/file_upload', function (req, res) {
console.log(req.file.name);
console.log(req.file.path);
console.log(req.file.type);
var file = __dirname + "/" + req.file.name;
console.log("File Name: " file);
fs.readFile( req.file.path, function (err, data) {
fs.writeFile(file, data, function (err) {
if( err ) {
console.log( err );
} else {
response = {
message:'File uploaded successfully',
filename:req.file.name
};
}
console.log( response );
res.end( JSON.stringify( response ) );
});
});
})
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
The file is successfully getting uploaded in /uploads directory, however, I am not able to open the file from there. Also, I am unable to print the name of the file when I try console.log(req.file.name); I get the output as undefined.
Any help will be appreciated. Thanks in advance.
EDIT: Console output as requested
Info: Start process (2:45:28 PM)
Example app listening at http://:::8081
undefined
uploads\3cbe4d0c18a778a9faddc6243c26b26a
undefined
File Name: undefined
{ message: 'File uploaded successfully', filename: undefined }
Process canceled
Info: End process (2:52:29 PM)

How to render a log file in browser through url using node js?

I am trying to render a log file in the browser by hitting a url. The log file is placed in my local (logs/app.log). I am stuck with this for a day.. Please find my node js code.
var app = express();
var path = require('path');
app.use('/logs', express.static(__dirname + '/logs'));
app.set('port', process.env.PORT || 3000);
var server = app.listen(app.get('port'), function() {
console.log('Express server listening on port ' + server.address().port);
});
Please help me to resolve this issue.
You can write an API as below:
app.get('/logs', function (req, res, next) {
var filePath = "path to your log file";
res.sendFile(filePath, function (err) {
if (err) {
next(err);
} else {
console.log('Sent the logs..');
}
});
});

Error reading a file with Node js

I can't read a file with this code that I've found on internet...
var express = require('express');
var app = express();
var fs = require('fs');
var port = 8080;
app.get('/', function(req, res) {
fs.readFile('./queries/anagconti_clienti_giorni.txt', 'utf8', function(err, data) {
if (err) {
res.send(err);
} else {
res.send(data);
}
});
});
var server = app.listen(port, function() {
console.log("Started on http://localhost:" + port);
});
The error that it give to me is:
{
"errno":-4058,
"code":"ENOENT",
"syscall":"open",
"path":"C:\Users\AlessandroGolin\Desktop\Mia\Visual_Studio\server_link\queries\anagconti_clienti_giorni.txt
"}
What could be causing this error??
Please cross check the path or permission of "./queries/anagconti_clienti_giorni.txt" file. If file not exist then create your "queries" folder at same level where your above code file exist.

(node:7016) [DEP0013] DeprecationWarning: Calling an asynchronous function without callback is deprecated

I want to upload the file from ajax to node.js.code is working perfectly.but it shows deprecated.like
(node:7016) [DEP0013] DeprecationWarning: Calling an asynchronous function without callback is deprecated.
what is the problem in nodejs code.can anyone solve the issue?Thankyou
var express = require('express');
var app = express();
var path = require('path');
var formidable = require('formidable');
var fs = require('fs');
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', function(req, res){
res.sendFile(path.join(__dirname, 'views/index.html'));
});
app.post('/upload', function(req, res){
console.log("get");
var form = new formidable.IncomingForm();
form.multiples = true;
form.uploadDir = path.join(__dirname, '/uploads');
form.on('file', function(field, file) {
fs.rename(file.path, path.join(form.uploadDir, file.name));
});
form.on('error', function(err) {
console.log('An error has occured: \n' + err);
});
form.on('end', function() {
res.end('success');
});
form.parse(req);
});
var server = app.listen(8086, function(){
console.log('Server listening on port 3000');
});
fs.rename() is asynchronous and takes a callback which is called when the rename is done. Node is warning you because you are ignoring this, which is usually a mistake.
You should probably at least check for errors, which should make the warning go away:
form.on('file', function(field, file) {
fs.rename(file.path, path.join(form.uploadDir, file.name), function(err){
console.log("Error renaming file:", err );
}
});
More here: https://nodejs.org/api/fs.html
fs asynchronous functions now demand a callback. You can fix your code by updating this line:
fs.rename(file.path, path.join(form.uploadDir, file.name));
by this one:
fs.rename(file.path, path.join(form.uploadDir, file.name),(error) => { /* handle error */ }))
You can check below documentation as well.
see https://nodejs.org/api/fs.html#fs_fs_writefile_file_data_options_callback

Extract function outside of main app.js

I'm fairly new to nodejs, and in wanting to keep the code neat and clean, I tried to extract a function to a different file, and then require it from my main app.
I'm facing a problem that this function includes socket-io data streaming and it uses the http module that uses my express app
This is the main app, and I want to move the content of getDetails to a seperate file:
const express = require('express');
const app = express();
const spawn = require('child_process').spawn;
const execFile = require('child_process').execFile;
const server = require('http').Server(app);
const io = require('socket.io')(server);
// Set router
const router = express.Router();
// fix body of requests
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
router.get('/getDetails', (req, res) => {
const qry = req.query;
if (qry.func === 'tail') {
const tail = spawn('ssh', ['root#' + qry.srv, qry.script, qry.func, qry.serv]);
io.on('connection', function (socket) {
tail.stdout.on('data', function (data) {
socket.emit('newLine', {line: data.toString('utf8').replace(/\n/g, '<br>')});
});
tail.on('close', (code) => {
console.log('child process exited with code', code);
});
tail.stderr.on('data', (data) => {
console.log('There are some errors:', data.toString('utf8'));
socket.emit('newLine', {line: data.toString('utf8')});
});
});
res.sendStatus(200);
}
else {
execFile('ssh', ['root#' + qry.srv, qry.script, qry.func, qry.serv], {timeout: 5000}, (error, stdout, stderr) => {
if (error) {
console.error('stderr', error);
return res.status(500).send({stderr: stderr, error: error});
}
return res.status(200).send({stdout: stdout.toString('utf8')});
});
}
});
app.use('/', router);
server.listen(port, function () {
console.log('The magic happens on localhost:' + port);
});
Now I can module.exports everything on my seperate file but do I need to also require express, and http again?
And should I move the server.listen to the seperate file?
server.js
const express = require('express');
const app = express();
const server = require('http').Server(app);
const io = require('socket.io')(server);
const route = require('./route');
// fix body of requests
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json())
app.set('socketio', io);
app.use('/',route);
server.listen(port, function () {
console.log('The magic happens on localhost:' + port);
});
route.js
const express = require('express');
const router = express.Router();
const Controller = require('./controller');
router.post('/register',Controller.getDetails);
module.exports=router;
controller.js
const spawn = require('child_process').spawn;
const execFile = require('child_process').execFile;
const controller = {
getDetails : (req,res)=>{
// now use socket.io in your controller file
var io = req.app.get('socketio');
const qry = req.query;
if (qry.func === 'tail') {
const tail = spawn('ssh', ['root#' + qry.srv, qry.script, qry.func, qry.serv]);
io.on('connection', function (socket) {
tail.stdout.on('data', function (data) {
socket.emit('newLine', {line: data.toString('utf8').replace(/\n/g, '<br>')});
});
tail.on('close', (code) => {
console.log('child process exited with code', code);
});
tail.stderr.on('data', (data) => {
console.log('There are some errors:', data.toString('utf8'));
socket.emit('newLine', {line: data.toString('utf8')});
});
});
res.sendStatus(200);
}
else {
execFile('ssh', ['root#' + qry.srv, qry.script, qry.func, qry.serv], {timeout: 5000}, (error, stdout, stderr) => {
if (error) {
console.error('stderr', error);
return res.status(500).send({stderr: stderr, error: error});
}
return res.status(200).send({stdout: stdout.toString('utf8')});
});
}
}
}
module.exports=controller;

Resources