简体   繁体   中英

Javascript -Node.js When do i need to 'require' a module

I'm fairly new to Node.js and server side programming in general, and still a bit confused about basic Node rules. To start an http server, I need to require the http module. The server itself returns a request and a response object, which (as I understand, correct me if I'm wrong) are both eventEmitters and stream objects. I can still use methods like req.on() and res.write() without requiring the stream and eventEmitter modules. However, when I try to use the pipe function req.pipe(res), an error occurs saying that the pipe function is not defined. I assume this happens because I didn't include the stream module. How come I can use certain stream functions without requiring modules, but not others?

It seems like you're pretty new to Javascript as well, but I'll try to do my best to explain this. require basically imports an object so you can use the functionality it provides. But if you already have an object, then you don't need to import ( require ) because it already exists.

For instance, if you want to create a stream, then you'll need to require it since creating a stream is a functionality you need to import. However, your function can still take a stream as a parameter and use it since it already exists.

const Stream = require('stream');

// need to require stream since we'd like to use it to create an object
const mystream = new Stream();

--

// no need to require stream here since you're given the object
function doSomethingWithStream(streamObject){
    streamObject.on('data', () => { /* do something */ });
}

So in your case you don't need to require stream since you already have the object. Although your res object should have a pipe method (see example below), but it won't work because piping only works from a Readable stream to a Writable stream and res is a Writable stream (see Node Stream docs).

const express= require('express');
const app = express();

app.get('/has-pipe',(req, res) => {
    const success = !!res.pipe; // true if res.pipe exists
    req.pipe(res) // Readable stream to Writable stream
    res.send({ success }); // returns true
})

const port = 3000
app.listen(port, () => console.log(`Example server running on port 3000`))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM