Asynchronous webserver in Node - javascript

Have a Node webserver(webserver.js) which serves file to clients browser. This webserver uses my file and api require("google-calendar.js");.
What is best practise to serve the google calendar result from Node to the webbrowser?
The webbserver wants to send pages syncronized but the google-api runs asynchronized which currently means result is showing up once the page is reloaded.
Below is the current code for doing this. All kind of feedback is appreciated.
www/index.html:
<html>
<head>
</head>
<body>
<iframe type="text/html" src="calendar.html"></iframe>
</body>
</html>
www/calendar.html:
CONTENT GENERATED BY webserver.js
webserver.js:
var port = 9800;
var serverUrl = "127.0.0.1";
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var http = require("http");
var path = require("path");
var fs = require("fs");
var url = require('url');
var checkMimeType = false;
var calendar = require('./google-calendar');
console.log("Starting web server at " + serverUrl + ":" + port);
var calPage = "";
function setCalendarPage(content) {
calPage = content;
console.log("Setting calendar content: " + calPage);
}
http.createServer(function(req, res) {
calendar.getEvents(setCalendarPage);
var request = req;
var filename = req.url;
console.log("====================");
console.log(filename);
if (filename == '/') {
filename = "/index.html";
}
sendFile(filename, res);
}).listen(port, serverUrl);
function getMimeType(filename) {
var ext = path.extname(filename);
var validExtensions = {
".html": "text/html",
".js": "application/javascript",
".css": "text/css",
".txt": "text/plain",
".jpg": "image/jpeg",
".gif": "image/gif",
".png": "image/png",
".woff": "application/font-woff",
".woff2": "application/font-woff2"
};
return validExtensions[ext];
}
function sendFile(filename, res) {
var localPath = __dirname;
localPath += ("/www" + filename);
fs.exists(localPath, function(exists) {
if (exists) {
let mimeType = getMimeType(filename);
getFile(localPath, res, mimeType);
} else {
console.log("File not found: " + localPath);
res.writeHead(404);
res.end();
}
});
}
function getFile(localPath, res, mimeType) {
fs.readFile(localPath, function(err, contents) {
if (!err) {
if (mimeType != undefined) {
res.setHeader("Content-Type", mimeType);
}
res.statusCode = 200;
if (localPath.includes("calendar")) {
var calContent = getHtmlPage(calPage);
res.setHeader("Content-Length", calContent.length);
res.end(calContent);
} else {
res.setHeader("Content-Length", contents.length);
res.end(contents);
}
} else {
res.writeHead(500);
res.end();
}
});
function getHtmlPage(text) {
var html = '<html><head>';
html += '<meta charset="UTF-8">';
html += '<title></title>';
html += '</head>';
html += '<body>';
html += text;
html += '</body>';
html += '</html>';
return html;
}
}
google-calendar.js:
const fs = require('fs');
const mkdirp = require('mkdirp');
const readline = require('readline');
const {google} = require('googleapis');
const OAuth2Client = google.auth.OAuth2;
const SCOPES = ['https://www.googleapis.com/auth/calendar.readonly'];
const TOKEN_PATH = 'credentials.json';
var result = "";
// Load client secrets from a local file.
module.exports = {
getEvents : function (callback){
if(result != ""){
return;
}
fs.readFile('client_secret.json', (err, content) => {
if (err) return console.log('Error loading client secret file:', err);
// Authorize a client with credentials, then call the Google Drive API.
return authorize(JSON.parse(content),callback);
});
}
};
/**
* Create an OAuth2 client with the given credentials, and then execute the
* given callback function.
* #param {Object} credentials The authorization client credentials.
* #param {function} callback The callback to call with the authorized client.
*/
function authorize(credentials,callback) {
const {client_secret, client_id, redirect_uris} = credentials.installed;
const oAuth2Client = new OAuth2Client(client_id, client_secret, redirect_uris[0]);
// Check if we have previously stored a token.
fs.readFile(TOKEN_PATH, (err, token) => {
if (err) return getAccessToken(oAuth2Client, callback);
oAuth2Client.setCredentials(JSON.parse(token));
return listEvents(oAuth2Client, callback);
});
}
/**
* Get and store new token after prompting for user authorization, and then
* execute the given callback with the authorized OAuth2 client.
* #param {google.auth.OAuth2} oAuth2Client The OAuth2 client to get token for.
* #param {getEventsCallback} callback The callback for the authorized client.
*/
function getAccessToken(oAuth2Client, callback) {
const authUrl = oAuth2Client.generateAuthUrl({
access_type: 'offline',
scope: SCOPES,
});
console.log('Authorize this app by visiting this url:', authUrl);
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
rl.question('Enter the code from that page here: ', (code) => {
rl.close();
oAuth2Client.getToken(code, (err, token) => {
if (err) return callback(err);
oAuth2Client.setCredentials(token);
// Store the token to disk for later program executions
fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) => {
if (err) console.error(err);
console.log('Token stored to', TOKEN_PATH);
});
callback(oAuth2Client);
});
});
}
/**
* Lists the next 10 events on the user's primary calendar.
* #param {google.auth.OAuth2} auth An authorized OAuth2 client.
*/
function listEvents(auth, callback) {
result = "";
const calendar = google.calendar({version: 'v3', auth});
calendar.events.list({
calendarId: 'primary',
timeMin: (new Date()).toISOString(),
maxResults: 10,
singleEvents: true,
orderBy: 'startTime',
}, (err, {data}) => {
if (err) return console.log('The API returned an error: ' + err);
const events = data.items;
if (events.length) {
console.log('Upcoming 10 events:');
events.map((event, i) => {
const start = event.start.dateTime || event.start.date;
console.log(`${start} - ${event.summary}`);
result += `${start} - ${event.summary} <br>`;
});
callback(result);
} else {
console.log('No upcoming events found.');
}
});
}

Related

youtube data api and node.js Error: Required parameter: part

var fs = require('fs');
var readline = require('readline');
var google = require('googleapis');
var googleAuth = require('google-auth-library');
// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/youtube-nodejs-quickstart.json
var SCOPES = ['https://www.googleapis.com/auth/youtube.readonly'];
var TOKEN_DIR = (process.env.HOME || process.env.HOMEPATH ||
process.env.USERPROFILE) + '/.credentials/';
var TOKEN_PATH = TOKEN_DIR + 'youtube-nodejs-quickstart.json';
// Load client secrets from a local file.
fs.readFile('client_secret.json', function processClientSecrets(err, content) {
if (err) {
console.log('Error loading client secret file: ' + err);
return;
}
// Authorize a client with the loaded credentials, then call the YouTube API.
authorize(JSON.parse(content), getChannel);
});
/**
* Create an OAuth2 client with the given credentials, and then execute the
* given callback function.
*
* #param {Object} credentials The authorization client credentials.
* #param {function} callback The callback to call with the authorized client.
*/
function authorize(credentials, callback) {
var clientSecret = credentials.installed.client_secret;
var clientId = credentials.installed.client_id;
var redirectUrl = credentials.installed.redirect_uris[0];
var auth = new googleAuth();
var oauth2Client = new auth.OAuth2(clientId, clientSecret, redirectUrl);
// Check if we have previously stored a token.
fs.readFile(TOKEN_PATH, function (err, token) {
if (err) {
getNewToken(oauth2Client, callback);
} else {
oauth2Client.credentials = JSON.parse(token);
callback(oauth2Client);
}
});
}
/**
* Get and store new token after prompting for user authorization, and then
* execute the given callback with the authorized OAuth2 client.
*
* #param {google.auth.OAuth2} oauth2Client The OAuth2 client to get token for.
* #param {getEventsCallback} callback The callback to call with the authorized
* client.
*/
function getNewToken(oauth2Client, callback) {
var authUrl = oauth2Client.generateAuthUrl({
access_type: 'offline',
scope: SCOPES
});
console.log('Authorize this app by visiting this url: ', authUrl);
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question('Enter the code from that page here: ', function (code) {
rl.close();
oauth2Client.getToken(code, function (err, token) {
if (err) {
console.log('Error while trying to retrieve access token', err);
return;
}
oauth2Client.credentials = token;
storeToken(token);
callback(oauth2Client);
});
});
}
/**
* Store token to disk be used in later program executions.
*
* #param {Object} token The token to store to disk.
*/
function storeToken(token) {
try {
fs.mkdirSync(TOKEN_DIR);
} catch (err) {
if (err.code != 'EEXIST') {
throw err;
}
}
fs.writeFile(TOKEN_PATH, JSON.stringify(token));
console.log('Token stored to ' + TOKEN_PATH);
}
/**
* Lists the names and IDs of up to 10 files.
*
* #param {google.auth.OAuth2} auth An authorized OAuth2 client.
*/
function getChannel(auth) {
var service = google.youtube('v3');
service.channels.list({
auth: auth,
part: 'snippet,contentDetails,statistics',
forUsername: 'GoogleDevelopers'
}, function (err, response) {
if (err) {
console.log('The API returned an error: ' + err);
return;
}
var channels = response.items;
if (channels.length == 0) {
console.log('No channel found.');
} else {
console.log('This channel\'s ID is %s. Its title is \'%s\', and ' +
'it has %s views.',
channels[0].id,
channels[0].snippet.title,
channels[0].statistics.viewCount);
}
});
}
I copied the code from youtube's data API tutorial for node.js
https://developers.google.com/youtube/v3/quickstart/nodejs
I entered the password from the link in the first time.
and now when I run the application I get this output:
The API returned an error: Error: Required parameter: part
this is part
part: 'snippet,contentDetails,statistics',
I guess this is not what you are asking for, but reverting back to version 24.0.0 worked for me:
excerpt from my packages.json
...
"googleapis": "24.0.0",
...

Getting contacts from google people api

const express = require('express'),
bodyParser = require('body-parser'),
Sequelize = require('sequelize')
const app=express()
app.use(bodyParser.json())
var google = require('googleapis');
var contacts = google.people('v1');
const nconf = require('nconf');
const readline = require('readline');
const plus = google.plus('v1');
const path = require('path');
const OAuth2Client = google.auth.OAuth2;
nconf.argv().env().file(path.join(__dirname, '/oauth2.keys.json'));
const keys = nconf.get('web');
const CLIENT_ID = '1058912681476-uat19si2uli37vlehs2avqfue2l0b6ku.apps.googleusercontent.com';
const CLIENT_SECRET = 'PbY8AVICTQsywb4qiqCJ8gMB';
const REDIRECT_URL = 'urn:ietf:wg:oauth:2.0:oob';
const oauth2Client = new OAuth2Client(CLIENT_ID, CLIENT_SECRET, REDIRECT_URL);
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
function getAccessToken (oauth2Client, callback) {
// generate consent page url
const url = oauth2Client.generateAuthUrl({
access_type: 'offline', // will return a refresh token
scope: 'https://www.googleapis.com/auth/plus.me' // can be a space-delimited string or an array of scopes
});
console.log('Visit the url: ', url);
rl.question('Enter the code here:', code => {
// request access token
oauth2Client.getToken(code, (err, tokens) => {
if (err) {
return callback(err);
}
// set tokens to the client
// TODO: tokens should be set by OAuth2 client.
oauth2Client.credentials=tokens;
callback();
});
});
}
// retrieve an access token
getAccessToken(oauth2Client, () => {
// retrieve user profile
plus.people.get({ userId: 'me', auth: oauth2Client }, (err, profile) => {
if (err) {
throw err;
}
console.log(profile.displayName, ':', profile.tagline);
});
});
//here-not working
contacts.people.connections.list({
auth: oauth2Client //authetication object generated in step-3
}, function (err, response) {
// handle err and response
if(err){
throw err;
}
console.log(response.names);
});
app.listen(8080)
I'm trying to get the contacts of an user from the google people api(https://developers.google.com/people/api/rest/v1/people.connections/list) but when I try to call contacts.people.connection.list() I get Error:
Missing required parameters: resourceName
at Object.createAPIRequest (/home/ubuntu/workspace/contactmanager/backend/node_modules/googleapis/build/src/lib/apirequest.js:94:18);
The error says it all. The resourceName is a required parameter. If you look in the people.connections.list you must provide a 'people/me' value as parameter. Other values are invalid.
GET https://people.googleapis.com/v1/{resourceName=people/me}/connections
#noogui already answered the reason . Here is the more elaborative code for the use case:
function listConnectionNames(auth) {
const service = google.people({
version: "v1",
auth
});
service.people.connections.list({
resourceName: "people/me",
pageSize: 10,
personFields: "names,emailAddresses"
},
(err, res) => {
if (err) return console.error("The API returned an error: " + err);
const connections = res.data.connections;
if (connections) {
console.log("Connections:");
connections.forEach(person => {
if (person.names && person.names.length > 0) {
console.log(person.names[0].displayName);
} else {
console.log("No display name found for connection.");
}
});
} else {
console.log("No connections found.");
}
}
);
}

javascript & google api : array work only debug mode

I don't understand why my code only works on debug mode. my variable musiques in my function createMusicBox() is an object in debug mode and null in not debuging
var musiques = [];
/**
* Create an OAuth2 client with the given credentials, and then execute the
* given callback function.
*
* #param {Object} credentials The authorization client credentials.
* #param {function} callback The callback to call with the authorized client.
*/
function authorize(credentials, callback) {
var clientSecret = credentials.installed.client_secret;
var clientId = credentials.installed.client_id;
var redirectUrl = credentials.installed.redirect_uris[0];
var auth = new googleAuth();
var oauth2Client = new auth.OAuth2(clientId, clientSecret, redirectUrl);
// Check if we have previously stored a token.
fs.readFile(TOKEN_PATH, function(err, token) {
if (err) {
getNewToken(oauth2Client, callback);
} else {
oauth2Client.credentials = JSON.parse(token);
callback(oauth2Client);
}
});
}
/**
* Lists the names and IDs of up to 10 files.
*
* #param {google.auth.OAuth2} auth An authorized OAuth2 client.
*/
function listFiles(auth) {
var service = google.drive('v3');
service.files.list({
auth: auth,
pageSize: 10,
fields: "nextPageToken, files(id, name)"
}, function(err, response) {
if (err) {
console.log('The API returned an error: ' + err);
return;
}
var files = response.files;
if (files.length == 0) {
console.log('No files found.');
} else {
musiques=files;
console.log('Files:');
for (var i = 0; i < files.length; i++) {
musiques[i] = files[i];
var file = files[i];
console.log('%s (%s)', file.name, file.id);
}
}
});
}
// this function pulls music in my google drive
function createMusicBox() {
// Load client secrets from a local file.
fs.readFile('client_secret.json', function processClientSecrets(err, content) {
if (err) {
console.log('Error loading client secret file: ' + err);
return;
}
// Authorize a client with the loaded credentials, then call the Drive API.
authorize(JSON.parse(content), listFiles);
});
console.log(musiques);
}
I find a solution, i put a callback in listFiles and now it works perfectly
function createMusicBox(event) {
// Load client secrets from a local file.
fs.readFile('client_secret.json', function processClientSecrets(err, content) {
if (err) {
console.log('Error loading client secret file: ' + err);
return;
}
// Authorize a client with the loaded credentials, then call the Drive API.
authorize(JSON.parse(content), listFiles, event);
});
}
function getNewToken(oauth2Client, callback) {
var authUrl = oauth2Client.generateAuthUrl({
access_type: 'offline',
scope: SCOPES
});
console.log('Authorize this app by visiting this url: ', authUrl);
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question('Enter the code from that page here: ', function(code) {
rl.close();
oauth2Client.getToken(code, function(err, token) {
if (err) {
console.log('Error while trying to retrieve access token', err);
return;
}
oauth2Client.credentials = token;
storeToken(token);
callback(oauth2Client);
});
});
}
function listFiles(auth, callback, event) {
var service = google.drive('v3');
service.files.list({
auth: auth,
pageSize: 10,
fields: "nextPageToken, files(id, name)"
}, function(err, response, listMusic) {
if (err) {
console.log('The API returned an error: ' + err);
return;
}
var files = response.files;
if (files.length == 0) {
console.log('No files found.');
} else {
callback(event, files);
}
});
}

When making multiple calls to google sheets API authentication doesn't work for second call: Request had insufficient authentication scopes

So basically what I've done here is I've hijacked the google sheets api node.js quickstart guide for my own purposes. Everything in here works great up until it hits my spreadsheets.batchUpdate and then everything gets wacky.
If I comment out the "auth" initialization in spreadsheets.batchUpdate I get the error message: The API returned an error: Error: The request does not have valid authentication credentials.
If I comment out the "auth" initialization in spreadsheets.batchUpdate I get the error message: The API returned an error: Error: Request had insufficient authentication scopes.
All I'm trying to do with these calls is get some data out of the sheet and then delete the rows after but I can't figure out this authentication issue.
var fs = require('fs');
var updateDB = require('./updateDB.js');
var readline = require('readline');
var google = require('googleapis');
var googleAuth = require('google-auth-library');
var splitData;
// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/sheets.googleapis.com-nodejs-quickstart.json
var SCOPES = ['https://www.googleapis.com/auth/spreadsheets.readonly'];
var TOKEN_DIR = (process.env.HOME || process.env.HOMEPATH ||
process.env.USERPROFILE) + '/.credentials/';
var TOKEN_PATH = TOKEN_DIR + 'sheets.googleapis.com-nodejs-quickstart.json';
var array = [];
var run = {
runQuickstart : function() {
// Load client secrets from a local file.
fs.readFile('client_secret.json', function processClientSecrets(err, content) {
if (err) {
console.log('Error loading client secret file: ' + err);
return;
}
// Authorize a client with the loaded credentials, then call the
// Google Sheets API.
authorize(JSON.parse(content), listMajors);
});
}
}
/**
* Create an OAuth2 client with the given credentials, and then execute the
* given callback function.
*
* #param {Object} credentials The authorization client credentials.
* #param {function} callback The callback to call with the authorized client.
*/
function authorize(credentials, callback) {
var clientSecret = credentials.installed.client_secret;
var clientId = credentials.installed.client_id;
var redirectUrl = credentials.installed.redirect_uris[0];
var auth = new googleAuth();
var oauth2Client = new auth.OAuth2(clientId, clientSecret, redirectUrl);
// Check if we have previously stored a token.
fs.readFile(TOKEN_PATH, function(err, token) {
if (err) {
getNewToken(oauth2Client, callback);
} else {
oauth2Client.credentials = JSON.parse(token);
callback(oauth2Client);
}
});
}
/**
* Get and store new token after prompting for user authorization, and then
* execute the given callback with the authorized OAuth2 client.
*
* #param {google.auth.OAuth2} oauth2Client The OAuth2 client to get token for.
* #param {getEventsCallback} callback The callback to call with the authorized
* client.
*/
function getNewToken(oauth2Client, callback) {
var authUrl = oauth2Client.generateAuthUrl({
access_type: 'offline',
scope: SCOPES
});
console.log('Authorize this app by visiting this url: ', authUrl);
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question('Enter the code from that page here: ', function(code) {
rl.close();
oauth2Client.getToken(code, function(err, token) {
if (err) {
console.log('Error while trying to retrieve access token', err);
return;
}
oauth2Client.credentials = token;
storeToken(token);
callback(oauth2Client);
});
});
}
/**
* Store token to disk be used in later program executions.
*
* #param {Object} token The token to store to disk.
*/
function storeToken(token) {
try {
fs.mkdirSync(TOKEN_DIR);
} catch (err) {
if (err.code != 'EEXIST') {
throw err;
}
}
fs.writeFile(TOKEN_PATH, JSON.stringify(token));
console.log('Token stored to ' + TOKEN_PATH);
}
/**
* Print the names and majors of students in a sample spreadsheet:
* https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
*/
function listMajors(auth) {
var sheets = google.sheets('v4');
sheets.spreadsheets.values.get({
auth: auth,
spreadsheetId: '1EV8S8AaAmxF3vP0F6RWxKIUlvF6uFEmsrOFWA1oNBYI',
range: 'Form Responses 1!A3:X3',
}, function(err, response) {
if (err) {
console.log('The API returned an error: ' + err);
return;
}
var rows = response.values;
//splitData = rows.split(',');
updateDB.inputFormToDB.apply(this, rows);
if (rows.length == 0) {
console.log('No data found.');
} else {
console.log('Form Responses');
for (var i = 0; i < rows.length; i++) {
var row = rows[i];
// Print columns A and E, which correspond to indices 0 and 4.
console.log('%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s', row[0], row[1], row[2], row[3], row[4], row[5], row[6], row[7], row[8], row[9],row[10], row[11], row[12], row[13], row[14], row[15], row[16], row[17], row[18], row[19], row[20], row[21], row[22], row[23]);
}
var spreadsheetId = '1EV8S8AaAmxF3vP0F6RWxKIUlvF6uFEmsrOFWA1oNBYI';
var requests = [];
requests.push({
"deleteDimension": {
"range": {
"sheetId": spreadsheetId,
"dimension": "ROWS",
"startIndex": 0,
"endIndex": 3
}
}
});
var batchUpdateRequest = {requests: requests}
var test = auth;
sheets.spreadsheets.batchUpdate({
// auth: test,
spreadsheetId: spreadsheetId,
resource: batchUpdateRequest
}, function(err, response) {
if (err) {
console.log('The API returned an error: ' + err);
return;
}
});
}
});
}
module.exports = run;
https://www.googleapis.com/auth/spreadsheets.readonly will give you read rights.
You need to use the https://www.googleapis.com/auth/spreadsheets scope to update the sheet.
https://www.googleapis.com/auth/spreadsheets.readonly
Allows read-only access to the user's sheets and their properties.
https://www.googleapis.com/auth/spreadsheets
Allows read/write access to the user's sheets and their properties.

Node.js error "terminate called after throwing an instance of 'std::bad_alloc' what(): std::bad_alloc"

I am using node.js on digital ocean and trying to run a file upload / download server.
To make sure the server runs in the background and does not quit on error, I am using the following
nohup nodejs server.js &
I am using nodejs instead of the node command because that is what digital ocean recommends.
This server is almost exlusively for uploading and downloading files. This works, for about two files, but then the server crashes with the following error:
"terminate called after throwing an instance of 'std::bad_alloc' what(): std::bad_alloc"
I have no idea what is causing this, and I would appreciate any help. Preventing the crash would be great but also making it so the node server would not crash would also be great. I thought that is what nohup does, but apparently not. (I also haven't been able to get forever working correctly).
Here is the code for my server:
var http = require('http'),
url = require('url'),
util = require('util'),
path = require('path'),
fs = require('fs'),
qs = require('querystring');
var formidable = require('formidable'),
mime = require('mime');
var account = {username: 'test', password: 'etc'};
var accounts = [account],
port = 9090,
function dirTree(filename) {
var stats = fs.lstatSync(filename),
info = {
name: path.basename(filename),
path: ip + ':' + port + '/uploads/finished/' + path.basename(filename),
type: mime.lookup(filename).substring(0, 5)
};
if (stats.isDirectory()) {
info.type = "folder";
info.children = fs.readdirSync(filename).map(function(child) {
return dirTree(filename + '/' + child);
});
}
return info;
}
http.createServer(function(request, response) {
if(request.method.toLowerCase() == 'get') {
var filePath = './content' + request.url;
if (filePath == './content/') {
filePath = './content/home.html';
}
if (filePath == './content/feed') {
a = dirTree('./content/uploads/finished');
response.end(JSON.stringify(a));
}
var extname = path.extname(filePath);
var contentType = mime.lookup(extname);
fs.exists(filePath, function (exists) {
if (exists) {
fs.readFile(filePath, function (error, content) {
if (error) {
response.writeHead(500);
response.end();
}
else {
response.writeHead(200, {'Content-Type': contentType});
response.end(content, 'utf-8');
}
})
} else {
response.writeHead(404);
response.end();
}
});
}
if (request.method.toLowerCase() == 'post') {
var form = new formidable.IncomingForm;
if (request.url == '/verify') {
form.parse(request, function (err, fields, files) {
for (i = 0; i < accounts.length; i++) {
if (fields.username == accounts[i].username && fields.password == accounts[i].password) {
fs.readFile('./content/uploadForm.html', function (error, content) {
if (error) {
response.end('There was an error');
} else {
response.end(content);
}
});
} else {
fs.readFile('./content/invalidLogin.html', function (error, content) {
if (error) {
response.end('There was an error');
} else {
response.end(content);
}
});
}
}
});
} else if (request.url == '/upload') {
var oldPath,
newPath,
fileName;
form.uploadDir = './content/uploads/temp/';
form.keepExtensions = true;
form.parse(request, function (err, fields, files) {
type = files['upload']['type'];
fileName = files['upload']['name'];
oldPath = files['upload']['path'];
newPath = './content/uploads/finished/' + fileName;
});
form.on('end', function () {
fs.rename(oldPath, newPath, function (err) {
if (err) {
response.end('There was an error with your request');
console.log('error')
} else {
response.end('<h1>Thanks for uploading ' + fileName + '<h1>');
}
});
});
}
}
}).listen(port);
console.log('listening on ' + port);
It looks like your script is just run out of the available memory.
Most likely you upload or download very large file and you read complete file in memory while receiving or sending.
You should rewrite you code using stream operations and process files chunk-by-chunk instead.

Categories

Resources