node.js
作者:互联网
Node.js 是一个基于 Chrome V8 引擎的 JS 运行环境
事件驱动、非阻塞式I/O的模型(轻量 高效)
下面我们开始通过简单的范例讲述 node.js 的使用
查询 node.js 的模块 API
选择需要的模块 API 做对应的事
简单的范例:
- 引用内置模块 操作文件
var fs = require('fs')
fs.readFile('index.txt', 'utf-8', function(err, data) {
if (err) throw err
if (data) {
var newStr = data.replace(/\d/gm, '') // 操作文件内容 去除多行中的数字
console.log(newStr)
fs.writeFile('newIndex.txt', newStr, function(err) {
if (err) throw err
console.log('write file OK...')
})
}
})
上面的代码通过 require
引入 node.js 的内置模块 FileSystem,并使用对应方法读写文件
- 我们同样可以引用我们自己写好的模块
function replaceStr(str) {
return str.replace(/\d/gm, '')
}
module.exports.replaceStr = replaceStr // 需要对外暴露的对象
然后对文件内容的操作就可以改为
var strApi = require('./replaceStrModal') // 上面自己写好的模块的文件名 replaceStrModal.js
// require 默认识别 js 文件
var newStr = strApi.replaceStr(data)
标签:node,fs,err,replaceStr,js,模块 来源: https://blog.csdn.net/Kofe_Chen/article/details/100704316