Looking to do output formatting (sprintf type functionality) in node.js, but before I write it myself I was wondering if there's something similar built-in (I've trawled the docs to no avail) or if someone's already written a module.
Many thanks
Looking to do output formatting (sprintf type functionality) in node.js, but before I write it myself I was wondering if there's something similar built-in (I've trawled the docs to no avail) or if someone's already written a module.
Many thanks
There is now printf-like support in util.format().
Example:
util.format('hello %s', 'world'); // Returns: 'hello world' util.format is very very basic: no %5d or %5.3f or anything like that, so it's not a real sprintf-like solution, unfortunately.var printf = require('util').format;var a = 1.234567;a.toFixed(3) => >'1.235'util.format does not support that (eg require('util').format("blarf_%04d", 42);) as of v 10.5.0.There are couple in the npm registry which are actual sprintf implementations since util.format has just a very basic support.
sprintf(" %s %s", title.grey, colors['blue'](msg)) ' \x1B[90mTitle\x1B[39m \x1B[34mMessage\x1B[39m'console.log works fine.
console.log('%d hours', 4); // 4 hours console.log('The %2$s contains %1$d monkeys', 4, 'tree'); // The tree contains 4 monkeys console.log('The %s contains %d monkeys', 'tree', 4); works in node v0.10.26.printf, not sprintf.`es6 template ${format}`As of now, there is a package that translate functions of other languages to Javascript such as php, python, ruby etc.
const sprintf = require("locutus/php/strings/sprintf") const data = sprintf("%01.3f", 2); console.log(data) //output: 2.000 Try it here codesandbox
util.format(format[, ...args])import { format } from "util"; const rawURL = "mongodb+srv://%s:%[email protected]"; const username = "zappbrannigan"; const password = "VMJta9hdDGymmYMz"; const url = format(rawURL, username, password); console.log(url); // Output: "mongodb+srv://zappbrannigan:[email protected]"