Coder Social home page Coder Social logo

rguerreiro / express-device Goto Github PK

View Code? Open in Web Editor NEW
307.0 8.0 42.0 786 KB

Device detection library for node.js based on the user-agent, built on top of express

Home Page: http://rguerreiro.github.io/express-device/

License: MIT License

JavaScript 89.69% HTML 10.31%

express-device's Introduction

express-device NPM version Downloads Build Status

Case you're interested only on the device type detection based on the useragent string and don't need all the express related stuff, then use the device package (https://www.npmjs.com/package/device) which was refactored from express-device for that purpose.

why express-device?

I'm really into node.js and lately I've been playing a lot with it. One of the steps I wanted to take in my learning path was to build a node.js module and published it to npm.

Then I had an idea: why not develop a server side library to mimic the behaviour that Twitter's Bootstrap has in order to identify where a browser is running on a desktop, tablet or phone. This is great for a responsive design, but on the server side.

how it came to be?

First I started to search how I could parse the user-agent string and how to differentiate tablets from smartphones. I found a couple good references, such as:

But then I came across with Brett Jankord's blog. He developed Categorizr which is what I was trying to do for node.js but for PHP. He has the code hosted at Github. So, express-device parsing methods (to extract device type) are based on Categorizr. Also I've used all of his user-agent strings compilation to build my unit tests.

how to use it?

From v0.4.0 express-device only works with express >= v4.x.x and node >= v0.10. To install it you only need to do:

$ npm install express-device

Case you're using express 3.x.x you should install version 0.3.13:

$ npm install [email protected]

Case you're using express 2.x.x you should install version 0.1.2:

$ npm install [email protected]

express-device is built on top of express framework. Here's an example on how to configure express to use it:

var device = require('express-device');

app.set('view engine', 'ejs');
app.set('view options', { layout: false });
app.set('views', __dirname + '/views');

app.use(bodyParser());
app.use(device.capture());

By doing this you're enabling the request object to have a property called device, which have the following properties:

NameField TypeDescriptionPossible Values
type string It gets the device type for the current request desktop, tv, tablet, phone, bot or car
name string It gets the device name for the current request Example: iPhone. If the option parseUserAgent is set to false, then it will return an empty string

Since version 0.3.4 you can now override some options when calling device.capture(). It accepts an object with only the config options (the same that the device supports) you which to override (go here for some examples). The ones you don't override it will use the default values. Here's the list with the available config options:

NameField TypeDescriptionPossible Values
emptyUserAgentDeviceType string Device type to be returned whenever the request has an empty user-agent. Defaults to desktop. desktop, tv, tablet, phone, bot or car
unknownUserAgentDeviceType string Device type to be returned whenever the request user-agent is unknown. Defaults to phone. desktop, tv, tablet, phone, bot or car
botUserAgentDeviceType string Device type to be returned whenever the request user-agent belongs to a bot. Defaults to bot. desktop, tv, tablet, phone, bot or car
carUserAgentDeviceType string Device type to be returned whenever the request user-agent belongs to a car. Defaults to car. desktop, tv, tablet, phone, bot or car
parseUserAgent string Configuration to parse the user-agent string using the useragent npm package. It's needed in order to get the device name. Defaults to false. true | false

express-device can also add some variables to the response locals property that will help you to build a responsive design:

is_desktop It returns true in case the device type is "desktop"; false otherwise
is_phone It returns true in case the device type is "phone"; false otherwise
is_tablet It returns true in case the device type is "tablet"; false otherwise
is_mobile It returns true in case the device type is "phone" or "tablet"; false otherwise
is_tv It returns true in case the device type is "tv"; false otherwise
is_bot It returns true in case the device type is "bot"; false otherwise
is_car It returns true in case the device type is "car"; false otherwise
device_type It returns the device type string parsed from the request
device_name It returns the device name string parsed from the request
In order to enable this method you have to pass the app reference to **device.enableDeviceHelpers(app)**, just after **app.use(device.capture())**.

Here's an example on how to use them (using EJS view engine):

<html>
<head>
    <title><%= title %></title>
</head>
<body>
    <h1>Hello World!</h1>
    <% if (is_desktop) { %>
    <p>You're using a desktop</p>
    <% } %>
    <% if (is_phone) { %>
    <p>You're using a phone</p>
    <% } %>
    <% if (is_tablet) { %>
    <p>You're using a tablet</p>
    <% } %>
    <% if (is_tv) { %>
    <p>You're using a tv</p>
    <% } %>
    <% if (is_bot) { %>
    <p>You're using a bot</p>
    <% } %>
    <% if (is_car) { %>
    <p>You're using a car</p>
    <% } %>
</body>
</html>

You can check a full working example here.

In version 0.3.0 a cool feature was added: the ability to route to a specific view\layout based on the device type (you must pass the app reference to device.enableViewRouting(app) to set it up). Consider the code below:

.
|-- views
    |-- phone
    |    |-- layout.ejs
    |    `-- index.ejs
    |-- layout.ejs
    `-- index.ejs

And this code:

var device = require('express-device');

app.set('view engine', 'ejs');
app.set('view options', { layout: true });
app.set('views', __dirname + '/views');

app.use(bodyParser());
app.use(device.capture());

device.enableViewRouting(app);

app.get('/', function(req, res) {
    res.render('index.ejs');
})

If the request comes from a phone device then the response will render views/phone/index.ejs view with views/phone/layout.ejs as layout. If it comes from another type of device then it will render the default views/index.ejs with the default views/index.ejs. Simply add a folder below your views root with the device type code (phone, tablet, tv or desktop) for the device type overrides. Several combinations are supported. Please check the tests for more examples.

You also have an ignore option:

app.get('/', function(req, res) {
    res.render('index.ejs', { ignoreViewRouting: true });
})

There's a way to force a certain type of device in a specific request. In the example I'm forcing a desktop type and the view rendering engine will ignore the parsed type and render as if it was a desktop that made the request. You can use all the supported device types.

app.get('/', function(req, res) {
    res.render('index.ejs', { forceType: 'desktop' });
})

View routing feature uses the express-partials module for layout detection. If you would like to turn it off, you can use the noPartials option (be advised that by doing this you can no longer use the master\partial layout built into express-device, but you can route to full views):

var device = require('express-device'); 

app.set('view engine', 'ejs');
app.set('view options', { layout: true });
app.set('views', __dirname + '/views');

app.use(express.bodyParser());
app.use(device.capture());

device.enableViewRouting(app, {
    "noPartials":true
});

app.get('/', function(req, res) {
    res.render('index.ejs');
})

contributors

where to go from here?

Currently express-device is on version 0.4.2. In order to add more features I'm asking anyone to contribute with some ideas. If you have some of your own please feel free to mention it here.

But I prefer that you make your contribution with some pull requests ;)

license

(The MIT License)

Copyright (c) 2012-2015 Rodrigo Guerreiro

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

express-device's People

Contributors

brycekahle avatar dkhurshudian avatar esco avatar hansmaad avatar lennym avatar lyxsus avatar marcellodisimone avatar rguerreiro avatar ryansully avatar saicheg avatar sitebase avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

express-device's Issues

Support car device type

Mozilla/5.0 (X11; u; Linux; C) AppleWebKit /533.3 (Khtml, like Gheko) QtCarBrowser Safari /533.3

What new features should I include for version 0.4?

One that is on the pipeline for a very long time is parsing the OS. But that is already done in the ua-parser package. Is it really necessary on the express-device?

What other ideas do you have that make sense on adding to express-device?

Docs incorrect

In the docs you list that emptyUserAgentDeviceType defaults to phone and unknownUserAgentDeviceType defaults to desktop but looking at your code I see the opposite.

Not sure if you're ever going to work on this code again, but in case someone else wants to use it and gets into the same issue I had

FTLOG please added example of in-Express use

can someone please add an example of how this works in Express itself

app.use(device.capture());

app.use(function(req,res,next){
   device.is_desktop ///  no indication that this is valid, please include example
   device.is_mobile /// no indication that this is valid, please include example to keep us from guessing
});

ubuntu install using NPM failure

I posted my error code below. This occurred from a ubuntu instance on ec2. You guy probably just need to update the registry.

npm http GET https://registry.npmjs.org/express-device npm http 304 https://registry.npmjs.org/express-device npm WARN git config --get remote.origin.urlreturned wrong result (git://github.com/publicclass/express-partials.git) execvp(): No such file or directory npm ERR! git clone git://github.com/publicclass/express-partials.git execvp(): No such file or directory npm ERR! Error:git "clone" "--mirror" "git://github.com/publicclass/express-partials.git" "/home/ubuntu/.npm/_git-remotes/git-github-com-publicclass-express-partials-git-4988eaf2" failed with 127

make 'desktop' default device.type or allow setting of default device via option

When a unknown user-agent requests a ressource, it gets detected as mobile. When no user-agent is set at all, it gets detected as desktop. That's not very consistent in my opinion.

The default device.type should be set to 'desktop' (makes it consistent with no user-agent set). Alternatively, we could expose an option to let us set the default device.type on initialization.

wget shows up as a phone

Thanks for your useful library, however there is one small issue: wget seems to be interpreted as a 'phone,' and I think it should be a 'bot.' Here is what I get when wgetting a simple page which simply res.sends the req.device:

{"parser":{"options":{"emptyUserAgentDeviceType":"desktop","unknownUserAgentDeviceType":"phone","botUserAgentDeviceType":"bot","carUserAgentDeviceType":"car","parseUserAgent":true},"useragent":{"family":"Wget","major":"1","minor":"16","patch":"3","device":{"family":"Other","major":"0","minor":"0","patch":"0"},"os":{"family":"Other","major":"0","minor":"0","patch":"0"}}},"type":"phone","name":"Other"} 

If I perform the same experiment using curl, then it correctly returns as a bot.

This was tested using: [email protected] [email protected] and [email protected]

Huge ReadME string is stored in memory

There's something weird going on with the publish history of this module. I cleaned my npm cache to make sure the issue wasn't on my end. When I install this module I get a package.json with the correct latest version 0.3.9 but it has a completely different JSON that includes the readme string. https://gist.github.com/esco/036ed9e2e374fa268e3b

The package.json in the master branch is fine because it doesn't have the "readme" field and when I download the tgz direclty it doesn't have it either.

Both package.json files have "version": "0.3.9".

The problem with this is that when express-device is required, the contents of ReadME.md are stored in require.cache which is a waste of memory.

Is anyone able to replicate this?

[DEP0005] DeprecationWarning: Buffer() is deprecated due to security and usability issues. Please use the Buffer.alloc(), Buffer.allocUnsafe(), or Buffer.from() methods instead.

$ yarn add express-device
yarn add v1.9.4
[1/4] Resolving packages...
[2/4] Fetching packages...
[-----------------------------------------------------------------------------------------------------------------] 0/881(node:18575) [DEP0005] DeprecationWarning: Buffer() is deprecated due to security and usability issues. Please use the Buffer.alloc(), Buffer.allocUnsafe(), or Buffer.from() methods instead.
info [email protected]: The platform "linux" is incompatible with this module.
info "[email protected]" is an optional dependency and failed compatibility check. Excluding it from installation.
[3/4] Linking dependencies...
[4/4] Building fresh packages...
success Saved lockfile.
success Saved 4 new dependencies.
info Direct dependencies
└─ [email protected]
info All dependencies
├─ [email protected]
├─ [email protected]
├─ [email protected]
└─ [email protected]
Done in 60.49s.

Hi, I am trying to use this library to support SSR (reference: mui/material-ui#6068 (comment)). I got the warning above, thought sharing with you.

Typescript support

Hey there

I've been using express for quite some time and recently switched to typescript.
The express-device package was always a must have for all my applications but now, i am missing the lack of typescript support.

Are there plans to create such support?
Thanks in advance.

Greetings

Googlebot on smartphone classified as "phone" instead of "bot"

I'm seeing the following user agents being detected as "phone":

Mozilla/5.0 (iPhone; CPU iPhone OS 8_3 like Mac OS X) AppleWebKit/537.36 (KHTML, like Gecko) Version/8.0 Mobile/12F70 Safari/600.1.4 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)

Mozilla/5.0 (iPhone; CPU iPhone OS 83 like Mac OS X) AppleWebKit/600.1.4 (KHTML like Gecko) Version/8.0 Mobile/12F70 Safari/600.1.4 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)

More complete list here:
https://support.google.com/webmasters/answer/1061943?hl=en

Seems to me they should be categorized as "bot" to be consistent with the fact bot-ness trumps device type for desktop. What do you think?

code markup with Native Node.js

How to use it with native Node.js with res.write and create server only (without Express and ejs)?

example:

const device = require('express-device')

http.createServer(function(req, res) {
  res.writeHead('blablabla')
  if (is_desktop) {
     res.write('hi desktop)
  }
  res.end()
}

thanks in advance

Request with iPad Safari is detected as desktop

Device type is returned as desktop in Safari, user agent:
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.1.1 Safari/605.1.15

But correctly as tablet in Chrome on the same device, user agent:
Mozilla/5.0 (iPad; CPU OS 14_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) CriOS/91.0.4472.80 Mobile/15E148 Safari/604.1

Facebook scraper detected as Mobile device

I make a simple patch in my node / express project

if(req.device.type != 'phone' || req.headers['user-agent'].indexOf('facebookexternalhit') !== -1) {
lang.page = '/';
res.render('index',lang);
} else {
lang.page = '/';
res.render('mobile/index',lang);
}

Small issue

This is more likely my goof up but I keep getting the message "device not defined".

I ran npm install express-device

the added this line to my server.js

app.use(device.capture());

I am also using express 3.

npm install failure on Windows Azure

maybe windows azure and some hosting services not support npm install using git...
dependent public npm repogitory. it's better support some cloud platforms.

i attach windows azure error log.

thank you. your module. it's very good. 👍

npm http GET http://registry.npmjs.org/express-device
npm http GET http://registry.npmjs.org/coffee-script
npm http 200 http://registry.npmjs.org/coffee-script
npm http GET http://registry.npmjs.org/coffee-script/-/coffee-script-1.6.1.tgz
npm http 200 http://registry.npmjs.org/express-device
npm http GET http://registry.npmjs.org/express-device/-/express-device-0.3.5.tgz
npm http 200 http://registry.npmjs.org/coffee-script/-/coffee-script-1.6.1.tgz
npm http 200 http://registry.npmjs.org/express-device/-/express-device-0.3.5.tgz
npm ERR! git clone git://github.com/publicclass/express-partials.git CreateProcessW: The system cannot find the file specified.
npm ERR! Error: `git "clone" "git://github.com/publicclass/express-partials.git" "C:\\DWASFiles\\Sites\\ssen\\Temp\\npm-13516\\1362820148766-0.6230687508359551"` failed with 127
npm ERR!     at ChildProcess.<anonymous> (D:\Program Files (x86)\nodejs\node_modules\npm\lib\utils\exec.js:56:20)
npm ERR!     at ChildProcess.emit (events.js:70:17)
npm ERR!     at maybeExit (child_process.js:358:16)
npm ERR!     at Socket.<anonymous> (child_process.js:463:7)
npm ERR!     at Socket.emit (events.js:67:17)
npm ERR!     at Array.<anonymous> (net.js:335:10)
npm ERR!     at EventEmitter._tickCallback (node.js:190:38)
npm ERR!  [Error: `git "clone" "git://github.com/publicclass/express-partials.git" "C:\\DWASFiles\\Sites\\ssen\\Temp\\npm-13516\\1362820148766-0.6230687508359551"` failed with 127]
npm ERR! You may report this log at:
npm ERR!     <http://github.com/isaacs/npm/issues>
npm ERR! or email it to:
npm ERR!     <[email protected]>

npm ERR! System Windows_NT 6.1.7601
npm ERR! command "D:\\Program Files (x86)\\nodejs\\\\node.exe" "D:\\Program Files (x86)\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "install" "--production"
npm ERR! cwd C:\DWASFiles\Sites\ssen\VirtualDirectory0\site\wwwroot
npm ERR! node -v v0.6.20
npm ERR! npm -v 1.1.37
npm ERR! message `git "clone" "git://github.com/publicclass/express-partials.git" "C:\\DWASFiles\\Sites\\ssen\\Temp\\npm-13516\\1362820148766-0.6230687508359551"` failed with 127
npmSetConsoleTitleW: The operation completed successfully.

README a bit confusing (parseUserAgent default)

This line:

Example: iPhone. If the option parseUserAgent is set to false, then it will return an empty string

Makes it seem like the default is true. At least to me. Totally your call. I'd suggest:

Example: iPhone. parseUserAgent is set to false by default and will return an empty string.

app.enableDeviceHelpers() and app.enableViewRouting() do not work

Hello, I have tried running the example application, and when I do, the following error stack is produced:

    app.enableDeviceHelpers();
        ^
TypeError: Object function app(req, res, next){ app.handle(req, res, next); } has no method 'enableDeviceHelpers'
    at Function.<anonymous> (/Users/ajay/Sites/pipeline/carbon/node/test.js:17:9)
    at Function.app.configure (/Users/ajay/Sites/pipeline/node_modules/express/lib/application.js:395:61)
    at Object.<anonymous> (/Users/ajay/Sites/pipeline/carbon/node/test.js:7:5)
    at Module._compile (module.js:449:26)
    at Object.Module._extensions..js (module.js:467:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Module.runMain (module.js:492:10)
    at process.startup.processNextTick.process._tickCallback (node.js:245:9)

It seems the two functions are not binding to express.application properly. I am using express 3.1.1.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.