Tag Archives: node.js

On and off of timer in JS

setInterval()
When a function
is called for a specified period of time:

setInterval(function,time,lang)

function: function to be called or code string to be executed
time: required parameters, every how long to call the function, in milliseconds
lang: optional parameters, running JScript | VBScript | JavaScript
clearInterval()
Means to stop the setInterval timer call function

function getTime() {
        console.log(123);
        if (true) {
            clearInterval(db)
        }
    }

let db = setInterval(getTime, 1000)

setTimeout()
Call a function after a certain time
syntax:

setTimeout(function,time,lang)

Function:
function: required, to be called
time: required, number of milliseconds to wait before executing code
lang: optional, script language: JScript | VBScript | JavaScript

Error: Cannot find module ‘express’

Problem description:
System: Windows 7 x64
Node.js version: Version is: V4.2.4 LTS
Introduction to Node.js: Notes on setting up the Node.js Web development environment under Windows 7
Sample code downloaded from IBM Bluemix. Error starting debugging locally: Error: Cannot find Module ‘Express’
The diagram below:

Solutions:
Just execute the command “NPM install” in the corresponding application directory, as shown in the figure below:

Before the above operation, the command “NPM install -g Express” was also executed, I wonder if it has any effect, as shown in the figure below:

= = = = = = = = = = = = = = = = = = = = = = = = = = = = I am separated line = = = = = = = = = = = = = = = = = = = = =
Please use a word to show that although you spend Valentine’s Day alone, but not lonely……
A: Where is my pump?
B: Watching ghost movies at night, I instantly feel someone in the kitchen, the toilet, the wardrobe, and under the bed. I don’t feel bored at all…
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
Valentine’s Day is the day when the mistress and the principal room rob a man, the day when the underground party rises to the surface, the day when the rose appreciates, and the day when the living are created! At 4 p.m., the florist smiled; At six o ‘clock in the evening, the owner of the restaurant smiled; At 9 p.m., the nightclub manager smiled; Midnight, the hotel owner smiled; The next day, the drugstore owner smiled; A month later, the gynecological hospital doctors and nurses all smiled.

failed: Error during WebSocket handshake: Unexpected response code: 400

Problem description: reference socket. Io in the project, after the project deployment error, local run no error
Reason for the error: You need to configure the information in the configuration file nginx.conf
Solutions:
Add in the location of the nginx file
Proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection “upgrade”.
The first line tells Nginx to use HTTP/1.1 when communicating with the Node backend, which is required by WebSockets. The next two lines tell Nginx to respond to the upgrade request, which is started by HTTP when the browser wants to use WebSocket. All three lines must be added.
Such as:

. Default_server;
listen [: :] : 80 default_server.
server_name localhost.
root/usr/share/nginx/HTML;
# Load configuration files for the default server block.
include /etc/nginx/default.d/*.conf;
The location/{
proxy_pass http://localhost:3100;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection “upgrade”.
proxy_set_header Host $Host;

}}

Node.JS “Cannot enqueue Handshake after invoking quit” Error (Fixed)

module.exports = {
    getDataFromUserGps: function(callback)
    {
        connection.connect();
        connection.query("SELECT * FROM usergps", 
            function(err, results, fields) {
                if (err) return callback(err, null);
                return callback(null, results);
            }
        ); 
        connection.end();
    },
    loginUser: function(login, pass, callback)
    {
        connection.connect();
        connection.query(
            "SELECT id FROM users WHERE login = ?AND pass = ?",
            [login, pass],
            function(err, results, fields) 
            {
                if (err) return callback(err, null);
                return callback(null, results);
            }
        ); 
        connection.end();
    },
    getUserDetails: function(userid, callback)
    {
        connection.connect();
        connection.query(
            "SELECT * FROM userProfilDetails LEFT JOIN tags ON userProfilDetails.userId = tags.userId WHERE userProfilDetails.userid = ?",
            [userid],
            function(err, results, fields)
            {
                if (err) return callback(err, null);
                return callback(null, results);
            }
        );
        connection.end();
    },
    addTags: function(userId, tags)
    {
        connection.connect();
        connection.query(
            "INSERT INTO tag (userId, tag) VALUES (?, ?)",
            [userId, tags],
            function(err, results, fields)
            {
                if (err) throw err;
            }
        )
        connection.end();
    }
}

Everything worked fine at first, but when I executed the second “query, “I got this error:

Cannot enqueue Handshake after invoking quit

I’ve tried turning off the connection without using the.end() method, but it doesn’t work.
Thanked first.
Radex
Those blind solutions and water paste I will not translate.
According to:
Fixing Node Mysql “Error: Cannot enqueue Handshake after invoking quit.”:
http://codetheory.in/fixing-node-mysql-error-cannot-enqueue-handshake-after-invoking-quit/

TL; Every time DR closes a connection you need to create a new connection using the createConnection method.
And
Note: If you are serving web requests, you should not turn off the connection each time the request is processed. When the server starts up, create a connection and keep querying it with the Connection/Client object. To handle server disconnection and reconnection events you can listen for error events. Complete code: Here.
Again according to:
The Readme. Md – Server disconnects:
https://github.com/felixge/node-mysql#server-disconnects
It said

Server disconnects
You may lose your connection to MySQL server due to a network problem, server timeout, or server hanging. All of these are considered “fatal errors “and there will be an error code err. Code = 'PROTOCOL_CONNECTION_LOST'. See the error handling section for more information.
The best way to handle these unwanted disconnections is as follows:

function handleDisconnect(connection) {
  connection.on('error', function(err) {
    if (!err.fatal) {
      return;
    }

    if (err.code !== 'PROTOCOL_CONNECTION_LOST') {
      throw err;
    }

    console.log('Re-connecting lost connection: ' + err.stack);

    connection = mysql.createConnection(connection.config);
    handleDisconnect(connection);
    connection.connect();
  });
}

handleDisconnect(connection);

As the example above shows, reconnection is achieved by creating a new connection, because the connection object is designed so that it cannot be reconnected once it dies.
When a connection pool is used, suspended connections are removed from the pool and space is freed, and a new connection is automatically created when a new connection request arrives.
the respondent has posted his own autoreconnect code at the end, so I’m not going to post it here.

The answer was 18:58 on May 3, 2013
XP1
Although this answer was not adopted by the main topic, but I and the following comments have always thought that this answer is better.
The original web site: http://stackoverflow.com/questions/14087924/cannot-enqueue-handshake-after-invoking-quit

Node-error cause analysis: Error: Multipart: Boundary not found

The front end USES umi-Request to upload the file and set it

The content-type headers: {‘ ‘:’ multipart/form – data ‘}

An error was reported when the back end received using Eggjs

nodejs.Error: Multipart: Boundary not found


Reason for the error: The Multipart did not find the Boundary
 
The upload file is a POST request form in multipart/form-data format

Content-type: The multipart/form-data did not follow the boundary
 
To sum up, the request header was set several times, overwriting the original form enctype= ‘multipart/form-data’
and finally finding the mutlipart/form-data in XHR. SetRequestHeader that overwriting the enctype setting in the form
To sum up: There is no need to set content-type: Mutipart /form-data repeatedly or it may overwrite the original and cause unexpected errors.


The Right way:
The front end

The back-end

The browser


https://blog.csdn.net/dongzhiliwansui/article/details/87896418

nodejs Error: Cannot find module ‘ejs‘

Error display:
Error: _resolveFilename (module.js:325:15)
at function.module._load (module.js:276:25)
at require (module.js:353:17)
at require
at new View (d:\WebClient\webstormSpace\ day6shuomodules \express\lib\view.js:78:30)
at eventemet.render (d: \ WebClient \ webstormSpace \ day6shuoshuo \ node_modules \ express \ lib \ application js: 569:12)
the at ServerResponse. Render (d:\WebClient\webstormSpace\ day6shuomodules \lib\ respons.js :961:7)
at exports. ShowIndex (d:\WebClient\webstormSpace\ day6shuoroutes.js :7:9)
at Layer. Handle [as handle_request] (d:\WebClient\webstormSpace\ day6shuomodules \express\lib\router\ pace.js: 93:5)
at next (d:\WebClient\webstormSpace\day6shuoshuo\node_modules\express\lib\router\route.js:131:13)Reason: EjS module is not installed
Solutions:
CMD goes to the project directory and installs EJS: NPM install –save EJS

Events.js:167 throw er appears when starting node service under linux; // Unhandled ‘error’ event solution

When starting the Node service under Linux, events.js:167 throw er appears; // The solution to this event has been Unhandled

pi@raspberrypi:~/ftp/files/node_nmusic $ node index.js 
events.js:167
      throw er; // Unhandled 'error' event
      ^

Error: listen EACCES 0.0.0.0:80
    at Server.setupListenHandle [as _listen2] (net.js:1317:19)
    at listenInCluster (net.js:1382:12)
    at Server.listen (net.js:1469:7)
    at Function.listen (/home/pi/ftp/files/node_nmusic/node_modules/express/lib/application.js:618:24)
    at Object.<anonymous> (/home/pi/ftp/files/node_nmusic/index.js:9:5)
    at Module._compile (internal/modules/cjs/loader.js:689:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
    at Module.load (internal/modules/cjs/loader.js:599:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
    at Function.Module._load (internal/modules/cjs/loader.js:530:3)
Emitted 'error' event at:
    at emitErrorNT (net.js:1361:8)
    at process._tickCallback (internal/process/next_tick.js:63:19)
    at Function.Module.runMain (internal/modules/cjs/loader.js:745:11)
    at startup (internal/bootstrap/node.js:266:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:596:3)

why
The Linux system cannot use ports below 1024 if the service is not started as root
The solution
Scenario 1: use 1024 or above port
scenario 2: use sudo as root

Express error: Failed to lookup view “error” in views directory processing

Express framework installs EJS templates by modifying them in app.js

app.set('views', path.join(__dirname, 'views/'));
app.engine('.html', require('ejs').renderFile);
app.set('view engine', 'html');

template for ejs, suffix to HTML after individual pages open tip Failed to lookup the view “error” in views directory error, found behind the template in a parameter is not passed so there is an error, but because the views directory under the lack of the error file resulting in this error, the solution is below the template directory to create a error file is used to output error information.

MongoNetworkError: failed to connect to server [localhost:27017]

MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connection 0 to localhost:27017 timed out
    at Socket.<anonymous> (D:\Desktop\node\mongodblearn\07_student_list\node_modules\mongodb\lib\core\connection\connection.js:355:7)     
    at Object.onceWrapper (events.js:427:28)
    at Socket.emit (events.js:321:20)
    at Socket._onTimeout (net.js:478:8)
    at listOnTimeout (internal/timers.js:549:17)
    at processTimers (internal/timers.js:492:7) {
  name: 'MongoNetworkError'
}]
    at Pool.<anonymous> (D:\Desktop\node\mongodblearn\07_student_list\node_modules\mongodb\lib\core\topologies\server.js:438:11)
    at Pool.emit (events.js:321:20)
    at D:\Desktop\node\mongodblearn\07_student_list\node_modules\mongodb\lib\core\connection\pool.js:562:14
    at D:\Desktop\node\mongodblearn\07_student_list\node_modules\mongodb\lib\core\connection\pool.js:995:11
    at callback (D:\Desktop\node\mongodblearn\07_student_list\node_modules\mongodb\lib\core\connection\connect.js:97:5)
    at D:\Desktop\node\mongodblearn\07_student_list\node_modules\mongodb\lib\core\connection\connect.js:124:7
    at _callback (D:\Desktop\node\mongodblearn\07_student_list\node_modules\mongodb\lib\core\connection\connect.js:349:5)
    at Connection.errorHandler (D:\Desktop\node\mongodblearn\07_student_list\node_modules\mongodb\lib\core\connection\connect.js:365:5)   
    at Object.onceWrapper (events.js:428:26)
    at Connection.emit (events.js:321:20) {
  name: 'MongoNetworkError'
}

The above error indicates that Mongodb is not started